text:
Q: keyboard automatic pops up when moving from one activity to another In my application when i go from one activity to another soft keyboard automatically pops up.
i have one activity(Say A) on which i have set
  android:configChanges="keyboardHidden"

because i don't want keyboard on this activity but when i move from this activity to another activity(say B) which contains Map and AutoComompleteTextView, keyboard first automatically pops up and then close down.
what i have tried on activity B:
In manifest i have set
android:windowSoftInputMode="stateHidden|adjustResize"

in oncreate
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

i also tried putting this in OnCreate
  try{
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }catch (Exception e)
    {
        Log.e(TAG, "onCreate: keyboard crash");
        e.printStackTrace();
    }

i also tried to set focus on another view in activity like(View v1)
 v1.requestFoucs();

i even tried putting
android:focusableInTouchMode="true"

on each and every component on activity B.
but nothing worked for me.
please help me to solve this problem
i have already tried all the accepted ans that belongs to list of links below:
OnScreen keyboard opens automatically when Activity starts
Automatic popping up keyboard on start Activity
How to avoid automatically appear android keyboard when activity start
this is my AutoComompleteTextView
<AutoCompleteTextView
            android:id="@+id/auto_serviceArea"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginStart="10dp"
            android:layout_weight=".5"
            android:background="@android:color/transparent"
            android:cursorVisible="false"
            android:hint="@string/serviceArea"
            android:padding="5dp"
            android:focusable="true"
            android:focusableInTouchMode="true"
            android:singleLine="true"/>

Edit 1: I tried to check that which view is getting focus so i can shift that focus, and while debugging i removed focus from AutoCompleteTextView but still keyboard appears and gone when activity starts.
So this is not an Autocomplete focus problem.

A: If you have tried everything that comes as an accepted ans according to your links for the ques, then why don't you try debugging your start activity, i mean on which you have put intent to start the respective activity.
While debugging one of my application i found that android soft keyboard has that problem of not going down even after finishing the activity that calls it, it stays on screen for few seconds but this doesn't happen frequently.
So i suggest you to debug your calling activity too just try putting "focusable=false" on the component from which you called the respective activity.

A: Simply what you need to do is to give
android:windowSoftInputMode="stateHidden"

in Manifest file of your Activity.

A: Write below line inside your main xml tag
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"

just as below
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true" >

A: Use these lines in java file:
InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);


text:
Q: RXJS subscribe providing Subject what is the useful thing for "Subscribe providing subject" and what does this mean:-
1- why I use subscribe providing subject
import { Subject, from } from 'rxjs';

const subject = new Subject<number>();

subject.subscribe({
  next: (v) => console.log(`observerA: ${v}`)
});
subject.subscribe({
  next: (v) => console.log(`observerB: ${v}`)
});

const observable = from([1, 2, 3]);

observable.subscribe(subject); // You can subscribe providing a Subject

// Logs:
// observerA: 1
// observerB: 1
// observerA: 2
// observerB: 2
// observerA: 3
// observerB: 3

A: You subscribe to an RxJS Observable with an Observer. This is the typescript interface for an observer.
interface Observer<T> {
  closed?: boolean;
  next: (value: T) => void;
  error: (err: any) => void;
  complete: () => void;
}

or a partial observer (just implement some of the callbacks) or with a function (which is the same as a partial observer with just the next callback.
It turns out that a Subject implements the Observer interface and so it can be used as an observer! This is a simple way to multicast a observable (and how the multicasting operators work to an extent).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Haskell variant of template metaprogramming I'm new to Haskell. Given the whole premise of Haskell is that a function will always return the same value, I'd expect there to be some way of e.g. calculating fibonacci values of constants at compile time, like I can do in C++ with template metaprogrmming, but I can't see how to do it. Is there a way?

A: edit: Daniel Fischer points out that you can lift an ordinary expression into Template Haskell and evaluate the result at compile-time, subject to certain constraints on the output type, by having an ordinary function fib and then splicing
$(let x = fib 1000 in [|x|])

Original answer follows.
As pointed out in comments, Template Haskell is the way to go for this.  For inductive functions like fibonacci, it's fairly straightforward.  You write code similar to a standard definition, but returning an ExpQ value.  Due to splicing restrictions, you'll need to use 2 modules.
{-# LANGUAGE TemplateHaskell #-}
module TH where

import Language.Haskell.TH

fibTH :: Int -> ExpQ
fibTH 0 = [| 0 |]
fibTH 1 = [| 1 |]
fibTH n = [| $(fibTH (n-1)) + $(fibTH (n-2)) |]

and
{-# LANGUAGE TemplateHaskell #-}
module Main where

import TH

y :: Int
y = $(fibTH 10)

main = print y

To confirm that the work is performed at compile-time, we can compile with -ddump-simpl to see the core, which confirms it.
Main.y :: GHC.Types.Int
[GblId,
 Caf=NoCafRefs,
 Str=DmdType m,
 Unf=Unf{Src=<vanilla>, TopLvl=True, Arity=0, Value=True,
         ConLike=True, WorkFree=False, Expandable=True,
         Guidance=IF_ARGS [] 10 20}]
Main.y = GHC.Types.I# 55

A: There's a great article by Don Stewart where he shows that using the LLVM backend with the right choice of flags will precompute certain functions at compile time and replace them with constants.


text:
Q: How can I space my triangle correctly? I am trying to print out a Right Triangle that looks like this:
                      1
                    2 1
                  3 2 1
              5 4 3 2 1
            6 5 4 3 2 1
          7 6 5 4 3 2 1
        8 7 6 5 4 3 2 1
      9 8 7 6 5 4 3 2 1
   10 9 8 7 6 5 4 3 2 1
11 10 9 8 7 6 5 4 3 2 1

The size of the triangle increases if the number in the method gets larger, which in this case is 11.
My code seems to only work up to 10 as after 10, my spacing is messed up.

                          1
                        2 1
                      3 2 1
                    4 3 2 1
                  5 4 3 2 1
                6 5 4 3 2 1
              7 6 5 4 3 2 1
            8 7 6 5 4 3 2 1
          9 8 7 6 5 4 3 2 1
        10 9 8 7 6 5 4 3 2 1
      11 10 9 8 7 6 5 4 3 2 1
    12 11 10 9 8 7 6 5 4 3 2 1
13 12 11 10 9 8 7 6 5 4 3 2 1
I am trying to make it so that up to 99, the spacing is correct. What kind of edits should I do to my if statements or for loops in order to space it properly?
Code:
public class Patterns
{

public static void main(String[] args)
{
    displayPattern(13);
    //displayPattern(11,",");
}
public static void displayPattern(int n)
{
    //print out n-1 spaces and the first number
    //print n-2 spaces and the 2nd then first number
    int counter = n;
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= counter; j++)
        {
            if (n > 10)
            {
                if (i == n)
                {
                    System.out.print("");
                }
                else if (i <= 10)
                {
                    System.out.print("  ");

                }
                else
                {
                    System.out.print("  ");

                }

            }
            else if (n <=10)
            {
                if (i>9)
                {
                    System.out.print(" ");
                }
                else
                {
                    System.out.print("  ");
                }
            }
        }
        System.out.print(i + " ");
        int tempValue = i - 1;
        while(tempValue>0)
        {
            System.out.print(tempValue);
            if(tempValue>1)
            {
                System.out.print(" ");
            }
            tempValue--;
        }
        if(tempValue==0)
        {
            System.out.print("\n");

        }
        counter--;
    }
}
}


text:
Q: ASP.NET Core Identity How to call an existing Login stored procedure using UserManager or SignInManager? Is it possible I have my existing DB structure and I want to create authorization and authentication from stored procedure.
But when I am using according to my requirement I get errors:
[Route("api/[controller]")]
[ApiController]
[AllowAnonymous]
public class AuthenticateController : ControllerBase
{
    private readonly UserManager<ApplicationUser> userManager;
    private readonly RoleManager<IdentityRole> roleManager;
    private readonly IConfiguration _configuration;
    private readonly ISqlApplicationUserRepository sqlApplicationUserRepository;

    public AuthenticateController(UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager, IConfiguration configuration, ISqlApplicationUserRepository sqlApplicationUserRepository)
    {
        this.userManager = userManager;
        this.roleManager = roleManager;
        _configuration = configuration;
        this.sqlApplicationUserRepository = sqlApplicationUserRepository;
    }
    [HttpPost]
    [Route("login")]
    public async Task<IActionResult> Login(SiteUser model)
    {
    //this function i want to use instead of .FindByNameAsync

        var user1 = sqlApplicationUserRepository.GetUserProfile(model.UserName);//this function i want to use instead of .FindByNameAsync

        var user = await userManager.FindByNameAsync(model.UserName);

    //so what change i need to do in this section ir in signinmanager to authenticate my user from membership tables using store procedure.
        if (user1 != null && await userManager.CheckPasswordAsync(user1, model.Password))
        {
            var userRoles = await userManager.GetRolesAsync(user1);

            var authClaims = new List<Claim>
            {
                new Claim(ClaimTypes.Name, user1.UserName),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            foreach (var userRole in userRoles)
            {
                authClaims.Add(new Claim(ClaimTypes.Role, userRole));
            }

            var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));

            var token = new JwtSecurityToken(
                issuer: _configuration["JWT:ValidIssuer"],
                audience: _configuration["JWT:ValidAudience"],
                expires: DateTime.Now.AddHours(3),
                claims: authClaims,
                signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                );

            return Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = token.ValidTo
            });
        }

        return Unauthorized();
    }
}


text:
Q: html() and click handler I initially got this code and all works well:

        <button id="sub" type="submit">
            Registo
        </button>

The problem now. When i add $(".rm").html("") with a button with the same id. If i click in this new button the page is reloaded. My question is. If the button added has the same id, why the click handler is not repeated ?
thanks

A: At the time you bind the event handler to $(".rm > #sub"), the new element does not exist yet, so jQuery cannot bind the handler to it.
You could either rebind the event handler, or bind it to $('.rm') instead and use event delegation (using .on()) :
$('.rm').on('click', '#sub', function() { // or use button instead of #sub
   //...
});

But instead of replacing the whole element, it seems you could just change its text content:
$('#sub span').text('Rever');
// or
$('.rm button span').text('Rever');

Also note that IDs are supposed to be unique, having two elements in the DOM with the same ID is invalid.

A: An id should be unique across a page.
To add the same action for all new dynamically created buttons, you need to do something like:
 $(".rm > .sub").live("click",function(event) {
....

But without using the same id, use a class instead as I have above.

A: The click function will traverse the DOM, and bind the event to all elements that exist at that point in time. You are creating a new DOM element later, which does not get bound.
To make this work out the way you want, see the jQuery documentation for the live() function.
The resulting change would look like:
$('#sub').live('click', function(event) {
    //your implementation
});

A: This happens because the events are bound in the unique DOM object regardless from id, when you remove the initial button and replace with one with same id the event bound to the button is gone.
What you can do is declare the event function in a variable and when you re-make your button, assign the event again to it.
Your code would be:
var btnEvent =  function(e) {
    e.preventDefault();
    var formdata = $("#custom").serialize();
    $.ajax({
        url: "dojo/insert.php",
        type: "post",
        dataType: "json",
        data: formdata,
        success: function(data) {
            switch (data.livre) {

            case 'error': {
                $(".rm").html('<button id="sub" type="submit" onclick="return btnEvent(event)">Rever</button>');

            } break;

            default:
                $('#paginas').delay(50).load('profile_empresa_3.php');
                break;
            }
        }
    });
return false;
};
$(document).ready(function() {
    $(".rm>#sub").click(btnEvent);
});

A: Use jQuery's .on() instead of .click() - http://api.jquery.com/on/


text:
Q: How to made custom Split array function in MS Excel? How to make a custom made function Split(str as String, delimiter as String ) using Split() in VBA to be used in worksheet.. and it will return as array or SPILL the result..
For example,
Split("{20;30;40;50;60}",";")

will return Spill down Array result in the same array as in the written formula as:
20
30
40
50
60

I try to use the Split(String,";") in VBA function but it only return 1 value and in text type..
I also need to remove both ' { ' and ' } ' in the string if there but accept it even if it is no there..

A: The UDF should use a two dimensional array:
Public Function splitt(s As String, sep As String)
    arr = Split(s, sep)

    ReDim arr2(0 To UBound(arr), 1 To 1)

    For i = LBound(arr) To UBound(arr)
        arr2(i, 1) = arr(i)
    Next i

    splitt = arr2
End Function

Example:

With Excel 365 ,  it will auto-spill.  Without Excel 365, it will need array-entry.

A: *

*Do not call your function Split

*Use Nested Replace

*We need to return a String array.

Function mysplit(str As String, deli As String) As String()
    mysplit = split(Replace(Replace(str, "{", ""), "}", ""), deli)
End Function

Then I would call it like this:
=LET(x,mySplit("{20;30;40;50;60}",";"),IF(ISNUMBER(--x),--x,x))

If you want it transposed then use TRANSPOSE
=LET(x,mySplit("{20;30;40;50;60}",";"),TRANSPOSE(IF(ISNUMBER(--x),--x,x)))

A single formula can do it all without the need of vba:
=FILTERXML(""&SUBSTITUTE(SUBSTITUTE(SUBSTITUTE("{20;30;40;50;60}",";",""),"}",""),"{","")&"","//b")


text:
Q: iptables + postfix cant send email Recently my host provider sent me a letter about some sort of attack from my server. I'm not into security so i found some tutorial and closed all unused ports with iptables.
Here is my iptables listing:
Chain INPUT (policy DROP)
target     prot opt source               destination
DROP       tcp  --  anywhere             anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/NONE
DROP       tcp  --  anywhere             anywhere            tcp flags:!FIN,SYN,RST,ACK/SYN state NEW
DROP       tcp  --  anywhere             anywhere            tcp flags:FIN,SYN,RST,PSH,ACK,URG/FIN,SYN,RST,PSH,ACK,URG
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:https
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:smtp
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssmtp
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:pop3
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:pop3s
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:imap2
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:imaps
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:ftp

Chain FORWARD (policy DROP)
target     prot opt source               destination

Chain OUTPUT (policy DROP)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:www state NEW
ACCEPT     tcp  --  anywhere             anywhere            tcp dpt:domain state NEW
ACCEPT     udp  --  anywhere             anywhere            udp dpt:domain state NEW
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:www
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:https
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:smtp
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:ssmtp
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:pop3
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:pop3s
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:imap2
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:imaps
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:ssh
ACCEPT     tcp  --  anywhere             anywhere            tcp spt:ftp

For some reason attack stopped, but i can no longer send emails.
-P OUTPUT ACCEPT works, but its not an option for me.
Need help ASAP. Thanks

A: When ACCEPTing outbound mail connections, you need to do so for dpt:smtp. The source port of outbound mail connections is randomized, it is not the smtp port.
More importantly, however, you need to figure out what was causing the attack, and if your system was compromised, you need to reinstall it to ensure the compromise does not remain available to the intruder.


text:
Q: Potential VBA solution for wanting a cell to update its manually inputed contents once data is entered in another cell I want data in the cells of column J to copy the data in the cells of column G once data is inputted into column G and not before.
However, prior to this replication taking place I would like to be able to manually update the price in the cells of column J.
See the attached photo for clarity.
Could anyone suggest a solution? I know VBA is a possibility, however, my Excel knowledge is not good enough to write code.
Yellow headings represent no formulas and blue represent formulas.
Excel_Worksheet_ TRADE LOG
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    With Target
        If .Count > 1 Then Exit Sub
        If Not Intersect(Range("C:C"), .Cells) Is Nothing Then
            Application.EnableEvents = False
            If IsEmpty(.Value) Then
                .Offset(0, -1).ClearContents
            Else
                With .Offset(0, -1)
                    .NumberFormat = "dd MMM yyyy"
                    .Value = Now
                End With
            End If
            Application.EnableEvents = True
        End If
    End With
    With Target
        If .Count > 1 Then Exit Sub
        If Not Intersect(Range("G:G"), .Cells) Is Nothing Then
            Application.EnableEvents = False
            If IsEmpty(.Value) Then
                .Offset(0, 12).ClearContents
            Else
                With .Offset(0, 12)
                    .NumberFormat = "dd MMM yyyy"
                    .Value = Now
                End With
            End If
            Application.EnableEvents = True
        End If
    End With
End Sub

A: A Simple Worksheet Change

*

*If values in the column range from G2 to the bottom-most (last) cell of the worksheet, are changed manually or via code, the values of the cells in the corresponding rows in column J will be overwritten with the values from column G.

*This solution is automated, you don't run anything.

Sheet Module e.g. Sheet1 (in parentheses in Project Explorer of Visual Basic Editor)
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)

    Const sCell As String = "G2" ' Source First Cell
    Const dCol As Variant = "J" ' Destination Column Id (String or Index)

    Dim irg As Range ' Intersect Range
    Dim cOffset As Long ' Column Offset
    With Range(sCell)
        Set irg = Intersect(.Resize(.Worksheet.Rows.Count - .Row + 1), Target)
        If irg Is Nothing Then Exit Sub
        cOffset = Columns(dCol).Column - .Column
    End With

    Dim arg As Range ' Current Area of Intersect Range
    Dim cel As Range ' Current Cell in Current Area of Intersect Range
    For Each arg In irg.Areas
        For Each cel In arg.Cells
            If Not IsError(cel.Value) Then
                cel.Offset(, cOffset).Value = cel.Value
            End If
        Next cel
    Next arg

End Sub


text:
Q: Cant call method of custom ConstraintLayout class? I want to make a custom ConstraintLayout so I can trigger some functions from the activity where its initialized.
I have the following code:
First initialized my custom view in layout:
<package.com.app.Main.LavadasView
        android:id="@+id/main_autolavados_lavadas_lavadas_view"
        android:layout_width="0dp"
        android:layout_height="25dp"
...
        />

This is my custom class LavadasView, constraint layout initialized from another XML file:
Java class
public class LavadasView extends ConstraintLayout {

    public LavadasView(Context context,AttributeSet attrs) {
        super(context);
//Inflate view from XML layout file
        LayoutInflater inflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.lavadas_view, this);

    }

    public void resetView(){
        //Some ui updates
    }

}

LavadasView xml file, just a normal constraint layout:
<?xml version="1.0" encoding="utf-8"?>

    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
</android.support.constraint.ConstraintLayout>

And in my Activity I get the instance with findViewByIdmehtod, then I want to call the resetView function and that gives me a null pointer exception related to LavadasView:
LavadasView lavadasView = (LavadasView) findViewById(R.id.main_autolavados_lavadas_lavadas_view);

//Call this method later on
        lavadasView.resetView();

SO what am I doing wrong? I've looked up and thats the correct way to get layout instance isnt?
Thanks.

A: The problem is with the constructor of your LavadasView. When your Activity is inflated it will call the LavadasView(Context context, AttributeSet attrs) constructor on you custom layout. In this constructor you need to call the super(context, attrs) for the ConstraintLayout to be properly inflated, but you're only calling super(context) which is why you get the NullPointerException.


text:
Q: The "core" of complete Erdős space This question is about the Erdős spaces:
$\mathfrak E=\{x\in \ell^2:x_n\in \mathbb Q\text{ for all $n<\omega$}\}$; and
$\mathfrak E_c=\{x\in \ell^2:x_n\in \mathbb P\text{ for all $n<\omega$}\},$
where $\ell^2$ is the Hilbert space, $\mathbb Q$ is the set of rational numbers, and $\mathbb P=\mathbb R\setminus \mathbb Q$.
I would like to know whether the Polish space $\mathfrak E_c$ contains a homeomorphic copy of either $\mathfrak E$ or $\mathbb Q \times \mathfrak E_c$, such that the complement of that copy is zero-dimensional.
Question 1. Let $X\subseteq \mathfrak E_c$ such that $\mathfrak E_c\setminus X$ is zero-dimensional.  Can we have  $X\simeq \mathfrak E$ or $\mathbb Q \times \mathfrak E_c$?
Note that a separable metrizable space $X$ has a completion with zero-dimensional remainder if and only if $X$ is rim-complete [2, Main Theorem (case $n=0$)].
Question 2. Are  $\mathfrak E$ and $\mathbb Q\times \mathfrak E_c$ rim-complete?
Note that $\mathbb Q\times \mathfrak E_c$ is a closed subspace of $\mathfrak E$ by [1, Corollary 9.5], so if $\mathfrak E$ is rim-complete then so is $\mathbb Q \times \mathfrak E_c$.
In the comments Taras Banakh noted that $\mathbb Q \times K$ cannot be rim-complete when $K$ is a compact space of positive dimension.
[1] Dijkstra, Jan J.; van Mill, Jan, Erdős space and homeomorphism groups of manifolds, Mem. Am. Math. Soc. 979, v, 62 p. (2010). ZBL1204.57041.
[2] Aarts, J. M., Completeness degree. A generalization of dimension, Fundam. Math. 63, 27-41 (1968). ZBL0167.51303.


text:
Q: Apachesolr search result sorting I'm trying to change sorting from apache Solr query.
for example bundle type: story, videogallery and category_management are indexed.
I wanted to show all results related to bundle type: category_management on top.
See attached screenshot:

Please help me to user Solr filter to sort my result.

A: The easiest way is to apply a boost to any entry that matches your requirement:
&bq=bundle:category_management^50

The weight - 50 - may have to be adjusted to get the result you want. This is faster than sorting by a function.
This will also still keep relevancy score inside each set of documents, compared to sorting by a function or adding a priority field for sorting.
If you want to actually apply a sort on multiple fields instead, you can first sort by a function that returns 1 for values that match and 0 for values that doesn't. Something like:
sort=if(termfreq(bundle,'category_management'),1,0),ds_changed desc


text:
Q: ROOT Library error So I installed Root 6.12.04 after I (unthinkingly) updated my OS to MacOS High Sierra. I cloned the git repository and followed all the steps on the "Quick Start" build root page. However something went wrong with my build and this is the error I get when I try to start a new instance of root and run Detector test:
dyld: lazy symbol binding failed: Symbol not found: __ZN5TROOT14RegisterModuleEPKcPS1_S2_S1_S1_PFvvERKNSt3__16vectorINS5_4pairINS5_12basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEEiEENSB_ISE_EEEES2_
  Referenced from: /Users/MM/repos/nsd-rootscripts/compile/NSDRootScriptsLib.so
  Expected in: /Users/MM/cern/root-build/lib/libCore.so
dyld: Symbol not found: __ZN5TROOT14RegisterModuleEPKcPS1_S2_S1_S1_PFvvERKNSt3__16vectorINS5_4pairINS5_12basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEEiEENSB_ISE_EEEES2_
  Referenced from: /Users/MM/repos/nsd-rootscripts/compile/NSDRootScriptsLib.so
  Expected in: /Users/MM/cern/root-build/lib/libCore.so
Does anyone know where the build went wrong?

A: This means that ROOT's dictionary interface has changed, but your dictionary sources (here: those in NSDRootScriptsLib.so) didn't get updated. Please re-generate the dictionaries.

A: This is not a solution, but may start you on the right track.
If you demangle the symbol name you posted with c++filt, you get
TROOT::RegisterModule(
  char const*,
  char const**,
  char const**,
  char const*,
  char const*,
  void (*)(),
  std::__1::vector<
    std::__1::pair<
      std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >,
      int
    >,
    std::__1::allocator<
      std::__1::pair<
        std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >,
        int
      >
    >
  > const&,
  char const**
)

So, the problem is that your linker can't find the definition of this TROOT::RegisterModule() function.
You said the problem was with libCore.so. Looking at my libCore.so with
objdump -x libCore.so | grep RegisterModule | c++filt

I can see that I have an identical symbol defined. If this command doesn't print anything for you, then your compilation must have gone wrong and didn't compile this function into the library.
Unfortunately, this is as far as I can get you.


text:
Q: How to fix SELECT statement and cookie counting in a foreach loop I'm trying to put data in a repeater and this works. Only I want an extra column with the amount of the id is in that cookie that is just read by the loop.
The text wil be put in a label somthing like this:
 <asp:Label ID="label2" runat="server" Text='<%# Eval( aantal ) %>' />
I tried like the follow things:
cmd.CommandText = "SELECT Naam, Prijs, GerechtId from [1A-Gerecht] WHERE GerechtId =('" + art + "') AND aantal = ('" + aantal + "')";

cmd.CommandText = "SELECT Naam, Prijs, GerechtId from [1A-Gerecht] WHERE GerechtId =('" + art + "')";
cmd.CommandText = cmd.CommandText + aantal;

The whole look likes the follow:
foreach(string art in mandje.Values.AllKeys)
{
    int aantal = int.Parse(mandje[art]);
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = (ConfigurationManager.ConnectionStrings["Hi"].ConnectionString);

    conn.Open();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "SELECT Naam, Prijs, GerechtId from [1A-Gerecht] WHERE GerechtId =('" + art + "')";

    cmd.ExecuteNonQuery();
    DataTable dt = new DataTable();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);
    d2.DataSource = dt;
    d2.DataBind();
    conn.Close();


text:
Q: Import Oracle Dump file and NOVALIDATE for FKs Situation:
I'm exporting data from the Oracle DB A, and importing it into an empty Oracle DB B.
When exporting from A, I deliberately export partially the data in different tables. That results into a dump file that for sure does not guarantee FK integrity due to the ignored data. Then I want to import it into the DB B it fails when creating the FKs.
Goal:
I want to have the same effect as NOVALIDATE has for FK Constraints but at import time. That is: for old data, it should not validate, and just check for new data. I didn't find a way to do it on the export, or import. Does any one know how can I do it?
Extra information:

*

*I can't change the FK on the DB A before dumping it.

*The data is so intertwined with old and new data, that there is no way to create the DB B while maintaining the consistency of FKs.

*I need to create the FKs, because the new data will rely on them


text:
Q: Firebase Storage / Google Places - async - await support I am moving my swift project to Swift 5.5, taking advantage of async await and trying to learn the syntax effectively while I am at it.
I have been successful so far in moving some functions across - those within the FirebaseFirestore database: ".getDocuments()" and ".setData".
In these instances, the compiler recognizes what I am trying to do and suggests the 'async throws' version of the method, leaving out the completion parameter / closure. See screen shot here:

When I try to do the same thing with FirebaseStorage method ".getData" I am not presented with such an option, and in fact, adding "try await" with a "do / catch" gives my the compiler error: "Missing argument for parameter 'completion' in call"
I also utilize the GooglePlaces API in my project, and the same thing happens here when I call the ".findAutocompletePredictions" and the ".fetchPlace". In these examples the compiler throws "Missing argument for parameter 'callback' in call"
How can I write these network calls using swift 5.5 async await?


text:
Q: PFQueryTableViewController with localizedCaseInsensitiveCompare Is there a way to make PFQueryTableViewController sort like NSStrings localizedCaseInsensitiveCompare?

A: Héctor Ramos (Solutions Architect at Parse.com) answers (in an email):

The localizedCaseInsensitiveCompare modified is iOS specific, however
  PFQuerys are executed on Parse's backend. This kind of sorting is not
  supported by Parse. I would suggest doing a query using the standard
  sort, then sorting the resulting array on the client side using a
  NSSortDescriptor with localizedCaseInsensitiveCompare.

Thank to Hector for his answer, which works - I did it. However it breaks pagination.


text:
Q: Extract data from a pdf into a table pdf example

I want to extract species information from a large pdf file (example in the image) into a list with each species as a row and the metadata as columns. Is there a way to do this in python or R?

A: Another way to do this is to simply use the pdftool library.
There are two parts of my solution:

*

*Put 1 paragraph (species) into one row of a data.frame

*Separate the information of the text into meta.data columns

Part 1: Set 1 species information per row of a data.frame:
# get the path of the pdf:
file_name <- "species_info.pdf"
# read the text in the pdf:
species.raw.text <- pdf_text(pdf = file_name, opw = "", upw = "")
# split the text into part. Each corresponding to 1 species
species.raw.text <- str_split(species.raw.text, "\n\n")
# convert the list into a data.frame i.e. each row = 1 species
species.df <- as.data.frame(species.raw.text)
# change the column name to raw.text
colnames(species.df) <- c("raw.text")

Part 2: Extract the information from the raw text into columns:
For this I used the dplyr library with the separate() function. I supposed that each species has the same type of information i.e.

*

*species name

*Gulf of Suez:

*Gulf of Aqaba:

*Red Sea main basin:

*General distribution:

*Remark:

I suggest this code to get what you want:
library(dplyr)
# remove the `\n`
species.df$raw.text <- gsub("\n", " ", species.df$raw.text)
# get the meta.data
species.df <- species.df %>%
  separate(
    col = raw.text, sep = "Gulf of Suez:",
    into = c("species.name", "rest")) %>%
  separate(
    col = rest, sep = "Gulf of Aqaba:",
    into = c("Gulf.of.Suez", "rest")) %>%
  separate(
    col = rest, sep = "Red Sea main basin:",
    into = c("Gulf.of.Aqaba", "rest")) %>%
  separate(
    col = rest, sep = "General distribution:",
    into = c("Red.Sea.main.basin", "rest")) %>%
  separate(
    col = rest, sep = "Remark:", fill = "right",
    into = c("General.distribution", "Remark"))

species.name
Gulf.of.Suez
Gulf.of.Aqaba
Red.Sea.main.basin
General.distribution
Remark

Carcharhinus albimarginatus (Rüppell 1837)
-
Israel (Baranes 2013).
Egypt (Rüppell 1837, as Carcharias albimarginatus), Sudan (Ninni 1931), Saudi Arabia (Spaet & Berumen 2015).
Red Sea, Indo-Pacific: East Africa east to Panama.
NA

Carcharhinus altimus (Springer 1950)
-
Egypt (Baranes & Ben-Tuvia 1978a), Israel (Baranes & Golani 1993).
Saudi Arabia (Spaet & Berumen 2015).
Circumglobal in tropical and warm temperate seas.
NA

Carcharhinus amboinensis (Müller & Henle 1839)
-
-
Saudi Arabia (Spaet & Berumen 2015).
Circumglobal in tropical and warm temperate seas, but not eastern Pacific.
NA

Carcharhinus brevipinna (Müller & Henle 1839)
Egypt (Gohar & Mazhar 1964, as Aprionodon brevipinna).
-
Egypt (Gohar & Mazhar 1964, as Aprionodon brevipinna and Carcharhinus maculipinnis), Saudi Arabia (Spaet & Berumen 2015).
Circumglobal in tropical and warm temperate seas, but not in the eastern Pacific.
Not a Lessepsian migrant as previously reported by Ben-Tuvia (1966) (see Golani et al. 2002).

Carcharhinus falciformis (Müller & Henle 1839)
-
-
Egypt (Gohar & Mazhar 1964, as Carcharhinus menisorrah), Saudi Arabia (Klausewitz 1959a, as Carcharhinus menisorrah; Spaet & Berumen 2015).
Circumglobal in tropical seas.
NA


text:
Q: How do I verify that $\sin (\theta)$ and $\cos (\theta)$ are functions? I am studying pre-calculus mathematics at the moment, and I need help in verifying if  $\sin (\theta)$ and $\cos (\theta)$ are functions? I want to demonstrate that for any angle $\theta$ that there is only one associated value of $\sin (\theta)$ and $\cos (\theta)$. How do I go about showing this?

A: Usually one begins studying the $\sin$ function in connection with right triangles. Here the notion of angle is not questioned, so I shall stick with this intuitive concept. It follows that we have $\sin \theta$ defined for $0\leq\theta\leq{\pi\over2}$.
As a next step one considers polar angles in the $(x,y)$-plane, measured counterclockwise from the positive $x$-axis, and one identifies these angles with the length of the corresponding arc on the unit circle $S^1$. When $0\leq\theta\leq{\pi\over2}$ then $\sin\theta$ is  the $y$-coordinate of the point where the second leg of the angle in question intersects $S^1$. It is then  natural to define $\sin \theta$ for all $\theta\in[0,2\pi]$ in this way, and a further step leads to the definition of $\sin\theta$ for all $\theta\in{\mathbb R}$: For arbitrary $\theta>0$ spool a thread of length $\theta$ counterclockwise around $S^1$ with initial point at $(1,0)$. The $y$-coordinate of the endpoint is then defined to be $\sin\theta$. It is then intuitively obvious that the function $\sin$ is periodic.
This sounds all very simple and natural. The difficulties begin when we try to make the above thought  process mathematically precise. In the first place we need a precise notion of angle: axiomatic euclidean geometry allows comparison and addition of angles, but does not provide an identification of angles with real numbers, which is inherent in the concept of the $\sin$ function.

A: The proof is based simply on similar triangles. If a right-angled triangle has an angle $\theta$ then the other two angles are $90^{\circ}$ and $(90-\theta)^{\circ}$. If two triangles have the same angles then they are similar.
My picture shows two similar triangles: $\triangle OAB$ and $\triangle OA'B'$.
Since $\theta = \angle AOB$ then, by definition
$$\sin\theta = \frac{\|AB\|}{\|OB\|}$$
Since $\theta = \angle A'OB'$ then, by definition
$$\sin\theta = \frac{\|A'B'\|}{\|OB'\|}$$
We can show that $\sin \theta$ has a single, unique value if we can show that the two ratios agree.
Let $T$ be the linear transformation given by an enlargement, centre $O$, with scale factor $\lambda$, such that $T(A) = A'$ and $T(B) = B'$. We have $\|A'B'\|=\lambda\|AB\|$ and $\|OB'\| = \lambda\|OB\|$, hence
$$\frac{\|A'B'\|}{\|OB'\|} = \frac{\lambda\|AB\|}{\lambda\|OB\|}=\frac{\|AB\|}{\|OB\|}$$
This shows that the ratio of the opposite side to the hypotenuse is the same for any two similar, right-angled triangles with angle $\theta$. That means that $\sin\theta$ is uniquely, well-defined.
(N.B. Similarity allows rotation and reflection as well as enlargement. However, rotations and reflections preserve lengths and so preserve ratios of lengths.)

A: I'm afraid that from a pre-calculus point of view, there is no consistent definition of the functional relationships that allows to discuss them as real functions (real valued in one real variable).
The big gap to be closed is the notion of an angle. In geometry, an angle is defined by a pair of rays from the same point. These most often occur at corners of triangles. All geometrically similar pairs of rays define the same angle. You can arrange such an equivalent pair of rays to have the first ray horizontal pointing to the right, then the second ray is uniquely characterized by a point on the unit circle (after fixing an origin and a unit length). The coordinates of that point then are the cosine and sine of that (equivalence class of) angle(s).
Then there are some angles that can be constructed and calculated geometrically by constructing regular n-gons and thus dividing the unit circle into n equal parts. n=3,4,6,8,12 are easy, n=5 is possible without too much effort. By bisection one can enclose any other angle in fractions of the full circle, starting from these known fractions, but this goes close to limit arguments, which already is calculus.
One can identify points on the unit circle with rotation matrices or complex numbers, which simplifies the angle arithmetic. Doubling an angle is then squaring the matrix or complex number, bisecting an angle corresponds to a square root. This gives functional equations that in their components are the trigonometric identities. Demanding continuity and differentiability at the zero angle will also give the trigonometric functions as unique solutions. However, this uniqueness is again enforced by calculus arguments.

A: It follows from the definition of $\sin(\theta)$ as a ratio of length of $\theta$'s opposite side to hypotenuse (Wikipedia).
As long as hypotenuse length is not equal to zero (otherwise the triangle degenerates into line or point), the division is a function which yields only one associated value.

A: More precisely, in Analysis, sin(x) is defined as the limit of a specific series.
Before, we know that the below series converges for every $x\in\mathbb{R}$:
$$\sum_{n=0}^\infty \frac{(-1)^n}{(2n+1)!}x^{2n+1}$$
And then we define :
$$\sin(x)=\sum_{n=0}^\infty \frac{(-1)^n}{(2n+1)!}x^{2n+1}$$
By this definition, $\sin(x)$ has all properties of the elementary definition (ratio of sides in a right-angled triangle).

A: If you want to verify this intuitively for yourself, then this answer could prove to be helpful. But remember, this is not a proof.
First try to visualize what $\sin\theta$ looks like. If you need some help, this is what it looks like.

Now remember that if $\sin\theta$ is a function, then for a certain $\theta$, there can be only one value of $\sin\theta$.
Now pick a random point on the $x-$axis. This is going to be your value for $\theta$. Now a draw a line perpendicular to the $x-$axis through that point. Now is it possible for that line to intersect the sine curve at more than one point? Try it out for different values of $x$. No, it is completely impossible for that line to intersect that curve at more than one point.
This means that for a certain $\theta$, there is only one associated value of $\sin\theta$.
$\sin\theta$ and $\cos\theta$ are pretty much the same. Notice that $\cos\theta=\sin(\theta +\frac{\pi}{2})$. So if you move the sine curve by $\frac{\pi}{2}$ to the right, you're going to get the curve for $\cos\theta$. And $\sin\theta$ and $\cos\theta$ look exactly the same. So you can use the same argument.
Finally, I repeat that this is not a proof. But I hope this helps you see it intuitively.
The figure is taken from here.


text:
Q: Angular schema form + highlight fields with errors on form load I am using angular schema form. The problem I have is, when I try to load the form there are some required attributes which are missing! The form doesn`t indicate about the missing properties. But when I click on that particular field and edit something and then remove it, it does show highlight the field for me. I want this to happen at initial loading as well. Looking for pointers. Thanks

A: You need to use required property in your form config schema:
//..other fields
"required": [
    "name",
    "email",
    "comment"
  ]

Check the demo here, it has required fields as well:
{
  "type": "object",
  "title": "Comment",
  "properties": {
    "name":  {
      "title": "Name",
      "type": "string"
    },//here validation details
    "email":  {
      "title": "Email",
      "type": "string",
      "pattern": "^\\S+@\\S+$",
      "description": "Email will be used for evil."
    },
    "comment": {
      "title": "Comment",
      "type": "string",
      "maxLength": 20,
      "validationMessage": "Don't be greedy!"
    }
  },//here naming fields required
  "required": ["name","email","comment"]
}

A: The property is validateOnRender: true
It needs to be added to the form's global options object.


text:
Q: GPU computation on Linux using open source kernel drivers Assuming freedom to choose whichever currently available GPU is most suited for the job, is it currently feasible to do GPU computation (either CUDA or OpenCL) on Linux using one of the open source GPU kernel drivers (i.e. not fgrlx or nvidia's binary driver)?

A: Not really. And it won't be supported for the foreseeable future. They still have so much work to do with just the graphics part that there is no time to develop the computing stack.
I personally relate to the closed drivers as I do to the actual HW, I cannot change the HW so I don't mind that I cannot change the drivers. Even though the closed drivers tend to be rather buggy and it takes ages for them to support new kernels and new X.org.

A: sharpneli already provided the right answer. However, I would like to also point out this article which indicates that there might be a change in thinking at least from AMD. But that will most likely take several month (years) before we will actually see a real open source driver that runs OpenCL.


text:
Q: React Native How to send multiple state variables from onClick child to method in parent class I'm having problems sending over data from my child class to its parent class.
Child class:
createItem = () => {
  const { newItemName } = this.state;
  const item = { newItemName };

  this.props.addItem(item);
  this.setState({ newItemName: '' });
  this.props.closeModal();
};

// Submit button
onPress={item => this.createItem(item)}

Parent class:
addItem = item => {
  // this.setState({name: item.name, quantity: item.quantity, location: item.location})

  this.setState({ name: item });
};

// Open Modal Button for data entry to be added to list
<TouchableOpacity
  style={styles.add}
  onPress={item => this.toggleModal(item)}
/>;

I'm not sure how to properly send the data over, I just know how to toggle the function in the parent class. I tried looking for answers online but they didn't match my scenario by sending data to a function and then changing the state of the parent class.


text:
Q: ER Diagram in Pgadmin for Postgresql in Ubuntu or Debian OS Please suggest how to create ER-diagram in PGAdmin or any other Debian package.

A: You can use dbeaver to do this. It allows you to export the ER diagram as png/svg etc.
DBeaver - https://dbeaver.io/
Git ref - https://github.com/dbeaver/dbeaver/wiki/Installation
Double click on a schema (eg, Schemas->public->Tables) and open the "ER Diagram" tab (next to "Properties" tab)

A: Beta Version in Pgadmin Does provide services for the ER diagram


text:
Q: What are the top statistic conferences to follow for applications in machine learning? What are the top statistic conferences to follow for applications in machine learning?
I just had a discussion, regarding that some of the machine learning jargon and buzzwords are not really sound for a top level statistician. So instead of machine learning conferences I would like to follow conferences on statistics (perhaps also journals) for possible applications in machine learning.
Perhaps someone could give me a short list of conferences were I could start searching?

A: The Joint Statistical Meetings are large annual statistical conferences.  To quote their site,

"JSM (the Joint Statistical Meetings) is the largest gathering of
  statisticians held in North America. It is held jointly with the
  American Statistical Association, the International Biometric Society
  (ENAR and WNAR), the Institute of Mathematical Statistics, the
  Statistical Society of Canada, and the International Chinese
  Statistical Association, and the International Indian Statistical
  Association"

If you search "machine learning" in their 2011 program, you get 68 hits.
Two other annual conferences are the meeting of the Eastern North American Region (ENAR) of the International Biometric Society and the meeting of its western counterpart WNAR.  Talks, posters, and sessions on machine learning have become a larger presence at these conferences over the last decade (you can find past years' programs in the links above -- the links to the actual programs weren't working for me this morning, however).


text:
Q: Is there a way to avoid X-Frame-Options in a CEF Windows Chromium Desktop App? I created a simple app using the suggested "app init", then I dropped a pre-compiled ReactApp in place.
The app has a browser within it that uses an IFrame to host the navigated pages, but in some pages, it issues the following error:
Refused to display 'https://www.theverge.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'.", source: http://localhost:5000/#/
https://content-security-policy.com/
The page above has a series of ways to how this could be avoided, and Chromium has a flag that could help, where it disables security and as many suggested in other posts and questions, that may help with this issue.
Beyond those, there is the possibility of writing a reverse-proxy that could potentially take care of this.
Either way what I need to know is if there is a way to achieve that through parameters within the "app" tool, something like:
app --unsecure
app publish --unsecure
app publish-exe --unsecure

Thank you

A: I've tried a number of different options inclusing using a Custom .NET Core Desktop Apps that adds the disable-web-security switch which used to work:
static int Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseStartup<Startup>()
        .UseUrls("http://localhost:5000/")
        .Build();

    host.StartAsync();

    var config = new CefConfig(Debug)
    {
        Args = args,
        StartUrl = startUrl,
        HideConsoleWindow = false,
        OnBeforeCommandLineProcessing = (processType, commandLine) => {
            commandLine.AppendSwitch("disable-web-security");
        }
    };

    return CefPlatformWindows.Start(config);
}

But no longer does so appears this security restriction is now embedded inside of Blink.
Using a Proxy to Remove Headers
The only solution I could get to work is to use a proxy that calls the internal .NET Core server which proxies the downstream URL but ignoring the X-Frame-Options header.
This is easy to do using ServiceStack's Proxy Feature where you can register a proxy to https://www.theverge.com that strips the X-Frame-Options header with:
Plugins.Add(new ProxyFeature(
    matchingRequests: req => req.PathInfo.StartsWith("/theverge"),
    resolveUrl: req => $"https://www.theverge.com" + req.RawUrl.Replace("/theverge", "/")) {
    IgnoreResponseHeaders = {
        "X-Frame-Options"
    }
});

This will let you embed The Verge in your App with:

Which will render TheVerge in an iframe as expected:

Working Demo
You can find a working example of this in ServiceStack.CefGlue.Win64.AspNetCore:
Startup.cs
public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseServiceStack(new AppHost());

        app.Run(context =>
        {
            context.Response.Redirect("/metadata");
            return Task.FromResult(0);
        });
    }
}

public class AppHost : AppHostBase
{
    public AppHost() : base("MyApp", typeof(MyServices).Assembly) { }

    public override void Configure(Container container)
    {
        Plugins.Add(new SharpPagesFeature());

        Plugins.Add(new ProxyFeature(
            matchingRequests: req => req.PathInfo.StartsWith("/theverge"),
            resolveUrl: req => "https://www.theverge.com" +
                                req.RawUrl.Replace("/theverge", "/")) {
            IgnoreResponseHeaders = {
                "X-Frame-Options"
            }
        });
    }
}

[Route("/hello")]
public class Hello : IReturn<HelloResponse>
{
    public string Name { get; set; }
}

public class HelloResponse
{
    public string Result { get; set; }
}

public class MyServices : Service
{
    public object Any(Hello request) =>
        new HelloResponse { Result = $"Hello, {request.Name}!" };
}

ServiceStack.CefGlue.Win64.AspNetCore.csproj
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="2.*" />
<PackageReference Include="ServiceStack.CefGlue.Win64" Version="5.*" />
<PackageReference Include="ServiceStack" Version="5.*" />
<PackageReference Include="ServiceStack.CefGlue" Version="5.*" />
<PackageReference Include="ServiceStack.CefGlue.Win64" Version="5.*" />
<PackageReference Include="WinApi" Version="4.0.0" />

You'll also need to copy CEF binaries from the ServiceStack.CefGlue.Win64 NuGet package with:
<ItemGroup>
    <Content Include="locales\*.*">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="swiftshader\*.*">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="*.pak">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="*.lib">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="*.dat">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="*.dll">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="*.bin">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    <Content Include="*.exe">
        <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
    </ItemGroup>

    <Target Name="CopyLinkedContentFiles" BeforeTargets="Build">
    <Copy SourceFiles="%(Content.Identity)"
            DestinationFiles="$(OutputPath)\%(Content.Link)"
            SkipUnchangedFiles="true"
            OverwriteReadOnlyFiles="true" />
</Target>

index.html
<!DOCTYPE html>

X-Frame-Options Proxy Test


text:
Q: Oracle locked sessions with ASP.Net I am connecting to an Oracle database in ASP.Net using SQLDataSource. My connection string is:
<add name="ConnectionString3"
 connectionString="Data Source=sml; User ID=sml; Password=sml; Unicode=True; Pooling=False;"
 providerName="System.Data.OracleClient"/>

Problem is that when I look at v$session on the database, I can see two locked sessions. They don't clear till I shutdown the ASP.Net server.
i.e. the query
select *
from v$session b
where status='INACTIVE' and schemaname='SML' AND program='w3wp.exe'

always shows two sessions which don't clear till I shutdown the server.
What is the proper way in ASP.Net to connect with an Oracle database and then manage the connections to clear after connecting with database? I meant how can I logout from the database after querying it?
Are there any session settings to do in the Oracle database?


text:
Q: Pass array value to colspan to create column table in php I am having a problem to pass a value from array to colspan, so I can have    dynamic multi column.
$my_values = array();
while ($data=mysqli_fetch_assoc($result)) {
 foreach ($data as $key => $value) {
   $my_values[] = $value;
 }
}
print_r($my_values);

and this is the output the I got for printing the $my_values:
Array ( [0] => 3 [1] => 2 [2] => 1 )

What I am trying to do here is creating table and pass those array to colspan:
$query = "SELECT * FROM assignments WHERE course_id=1";
        $result1 = mysqli_query($conn, $query);
        if (mysqli_num_rows($result1) != 0) {
        while ($row=mysqli_fetch_assoc($result1)) {
          echo ''.$row['assignment_name'].'	';
        }
      }

where is $my_values['0'] will get just 3. what I am trying to do here is I want to get index 0 first, then index 2 then index 3. so the first one can create 3 columns and the second one 2 columns and the third 1 columns.
can you help me guys with this issue?

A: Use below code. it may help you with
$query = "SELECT * FROM assignments WHERE course_id=1";
        $result1 = mysqli_query($conn, $query);
        if (mysqli_num_rows($result1) != 0) {
            $i = 0; //-------------->INITIALIZE THE VARIABLE
        while ($row=mysqli_fetch_assoc($result1)) {
          echo ''.$row['assignment_name'].'	';
          $i++; //----------------> INCREMENT THE VARIABLE
        }
      }


text:
Q: Ayuda con una validacion, renvio a otra pagina php Necesito ayuda! tengo una validacion simple de una variable introducida por el usuario llamada "codigo" que tiene que consultar en la base de datos, (eso funciona), el problema es que Si el "codigo" existe en SQL debe enviar al usuario a prevsecurtihost.php pero si no coincide con ninguno debe de enviar al usuario a denegada.php o aparecer un mensaje de error no importa.
El problema esta en el bendito header, que si lo meto dentro del if, me dice el error "
Warning: Cannot modify header information - headers already sent by (output started at /storage/ssd3/530/13900530/public_html/conexion.php:1) in /storage/ssd3/530/13900530/public_html/redirigir.php on line 39" (y si para solucionarlo lo pongo al principio luego de session start, ya no valida nada y me abre, este bien o no el codigo de ingreso la pagina prevsecurtihost.php)
ya agote todas las ideas que se me ocurrieron hasta incluso invente variables pero ni asi funciona.
login.php ---> abre session del usuario (con usuario y clave)
chacklogin.php---> valida session y envia a paneldecontrol.php
panel de control.php----> es donde el usuario ya registrado ingresa en una form de un solo input el "codigo" ese que solicito y luego preciona consulta para enviar eso al validador redirigir.php.
*redirigir.php---> es con el que tengo el problema luego de validar debe de enviar a prev.. o a deneg...
prevsecurtihost.php---> es a donde tiene que ir si el codigo coincide con el que hay en la base.
denegada.html---> o el mensaje simple de que no es correcto (mucho mejor si es asi) es el que tiene que aparecer si no coincide.
redirigir.php
    <?php
session_start();

$nombre = $_POST['nombre'];

$link = $nombre.'.php';

$_SESSION['id'] = $nombre;

//$ok = header("location: prevsecurityhost.php");

//$no = header("location: denegado.html");

include 'conexion.php';

 $conexion = new mysqli($host_db, $user_db, $pass_db, $db_name);

 if ($conexion->connect_error) {
 die("La conexion falló: " . $conexion->connect_error);
}

 $buscarcodigo = "SELECT * FROM $tbl_name
 WHERE codigo = '$_POST[nombre]' ";

 $result = $conexion->query($buscarcodigo);

 $count = mysqli_num_rows($result);

 if ($count == 1) {

    header("location: prevsecurityhost.php");

 }
 else{

echo 'datos incorrectos a sido expulsado del sistema' ;

?>

<button type="button" class="btn btn-success"> Cerrar Sesion</button>

<?php

}

?>

prevsecurityhost.php
 <?php

session_start();

header( "refresh:9;url=encoderbanswichof.php" );

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {

} else {
   echo "Inicia Sesion para acceder a este contenido.
";
   echo "
Login";
   echo "

Registrarme";
   header('Location: http://localhost/login/login.html');//redirige a la página de login si el usuario quiere ingresar sin iniciar sesion

exit;
}

$now = time();

if($now > $_SESSION['expire']) {
session_destroy();
header('Location: http://localhost/login/login.html');//redirige a la página de login, modifica la url a tu conveniencia
echo "Tu sesion a expirado,
Inicia Sesion";
exit;
}
?>

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

  <form class="modal-content animate" action="checklogin.php" method="post">

.

<?php
       $_SESSION['id'];

 ?>

  </form>

A: Puesdes hacerlo de la siguiente manera

<?php
session_start()
if(isset($_SESSION["id"]))
{
//tu codigo
}
else
{
header("location:http://localhost/login/login.html");
}
?>

Recuerde que header() debe ser llamado antes de mostrar nada por pantalla, etiquetas HTML, líneas en blanco desde un fichero o desde PHP. Es un error muy común leer código con funciones como include o require, u otro tipo de funciones de acceso de ficheros que incluyen espacios o líneas en blanco que se muestran antes de llamar a la función header(). Sucede el mismo problema cuando se utiliza un solo fichero PHP/HTML.


text:
Q: Content-Disposition inline filename issue with IE I am displaying a pdf in browser with inline from API using an aspx page.
While saving the pdf using Chrome/Firefox, takes the filename from header("Content-Disposition", "inline;filename=xyz.pdf")
But while saving the pdf using IE it does not reads the filename from header("Content-Disposition", "inline;filename=xyz.pdf"). instead it takes the aspx name.
Technical details
I have an xyz.aspx page.
The xyz.aspx page will invoke an API for a document.
Then the downloaded document from API will transferred to browser with inline to display the pdf document.
Am setting the response header as below and writing the file bytes.
            HttpContext.Current.Response.ClearHeaders();

            Response.AddHeader("Content-Disposition", "inline;filename=\"" + Name + "\"");

            HttpContext.Current.Response.ContentType = "application/pdf";

*

*Issue:
While saving the opened pdf in IE it takes xyz.aspx instead of the name from header.

*Requirement:
While saving the pdf using IE, it need to save with the name of pdf.
I googled so much, as every one tells its IE behavior. I hope some one knows a solution.
Note: I have to display the pdf in browser and then save. Not to download using "attachment"

A: It is true some versions of IE can't handle ("Content-Disposition", "inline;filename=...")
This is because filename=... was originally intended for the attachment disposition. Not all browser-based PDF viewers can handle it.
The only solution I see is to allow access via a different url.
Suppose you have a route to the pdf like: /pdf/view. If you change it to /pdf/view/filename and you configure your application to handle this route in the same way as /pdf/view your problem is solved.
You can also re-write the download url on the webserver.
Depending on your webserver you have various ways of doing this.

A: I have also tried with all kind of headers and methods.
In the end, my solution was
    private FileResult ReturnStreamAsPdf(string fileName, Stream stream)
    {
        ContentDisposition cd = new ContentDisposition
        {
            FileName = fileName,
            Inline = true  // false = prompt the user for downloading;  true = browser to try to show the file inline
        };
        Response.Headers.Add("Content-Disposition", cd.ToString());
        Response.Headers.Add("X-Content-Type-Options", "nosniff");

        return new FileStreamResult(stream, MediaTypeNames.Application.Pdf);
    }

and the Route Attribute on the method:
    [Route("api/getpdfticket/{ticketnumber}")]
    public async Task<FileResult> GetPdfTicket(string ticketnumber)

And the href:
href="@($"/api/getpdfticket/{product.TicketNumber}.pdf")"
It seems like Microsloft is still inventing their own standards:
http://test.greenbytes.de/tech/tc2231/#inlwithasciifilenamepdf
PDF Handler : content-disposition filename


text:
Q: How to set the mime-type of a new created file to application/json? C++ I am creating a json string in C++ and save it to a file using fstream.
Here is the code for creating the file:
  string json="{ \"a\"= 1 }";

  fstream datei1("jsonfile.json",ios::out);
  file1 << json << endl;
  file1.close();

How could one set the mime-type to 'application/json'??
file -i jsonfile.json in linux shell gives me: jsonfile.json: text/plain; charset=utf-8

A: file command try to guess the type of your file by reading it.
And read your file again: it is a plain text file. There is only a simple object stored, nothing that can lead to the application answer.
So without changing your file data, there is nothing you can do from your code to change file command answer.

A: From the documentation of file command:

Causes the file command to output mime type strings rather than the
  more traditional human readable ones. Thus it may say 'text/plain;
  charset=us-ascii' rather than 'ASCII text'. In order for this option
  to work, file changes the way it handles files recognized by the
  command itself (such as many of the text file types, directories etc),
  and makes use of an alternative 'magic' file. (See the FILES section,
  below).
/usr/share/file/magic.mgc Default compiled list of magic.
/usr/share/file/magic Directory containing default magic files.

You can read about magic files on the wiki.
Also you can add your own signatures in /etc/magic.
But *.json is a plain text file, without any signatures, thus, probably, it's impossible to make OS think, that some file has application/json mime type without any hacks.


text:
Q: Merge excel files from 2 folders with output to another folder i have 3 xlsx files in 2 subfolders of main folder. is there a way in python to take check same name files from both folders and combine into new excel file with outputs from both in different tabs (tab names should be folder name)
Input:
Desktop\main_folder\folder_a\test1.xlsx
Desktop\main_folder\folder_a\test2.xlsx
Desktop\main_folder\folder_a\test3.xlsx

Desktop\main_folder\folder_b\test1.xlsx
Desktop\main_folder\folder_b\test2.xlsx
Desktop\main_folder\folder_b\test3.xlsx

Output:
Desktop\main_folder\folder_c\test1.xlsx

(sheet 1 : data from folder a [sheet name folder_a])
(sheet 2 : data from folder b [sheet name folder_b])
code

A: Yes, you can use os.listdir() to list all files in your folder_a and folder_b and collect those file names into a list. You can later create a loop to check for file name that exist in both folder. Then use Python Excel modules such as openpyxl or XlsxWriter to create new worksheet in the existing excel workbook and move the excel worksheet from another workbook to the new worksheet.


text:
Q: Google Drive Auto Unzip In Situ (i.e. in Google Drive) a Google Takeout archive after upload Id like to know if the following is possible as I can't seem to find any concrete way to do it online:
When Google Takeaway service uploads a new takeout-xxx.zip file to my Google Drive Takeaway folder, can a Google Drive script run to automatically extract that zip file and all contents to a folder within my Google Drive account in the cloud?
If possible, if anyone was able to provide some starter code that'd be awesome.
Many thanks

A: Yes, you can automatically extract zip file within Google drive by using 'ZIP Extractor'. Using ZIP Extractor you can choose which files in the zip file to extract after extracting the ZIP file, It can read ZIP files from Google Drive and extract their contents into Google Drive.
Here's a Official documentation for Zip Extrator: https://developers.google.com/drive/v3/web/examples/
Link below is a demo app for ZIP Extractor: https://github.com/googledrive/zipextractor


text:
Q: Unusual normalization related to the eigenvector perturbation In the Magnus and Neudecker's book "Matrix differential calculus with applications", Sec. 8.9, the authors derive an expression for the derivative of the right eigenvector $u(t)$ corresponding to a simple eigenvalue $\lambda(t)$ of a matrix $Z(t)\in M_n(\mathbb C)$:
$$u'(0)=(\lambda I -Z(0))^\dagger \left(I-\frac{u(0)v^*(0)}{v^*(0)u(0)}\right)Z'(0)u(0),$$
where $()^\dagger$ is the Moore-Penrose inversion operator and $v^T(t)$ is the  left eigenvector.
When deriving this expression they normalize $u(t)$ s.t. $\langle u(t),u(0)\rangle=1$ for small $t$, thus basically requiring that $\langle u'(0),u(0)\rangle=0$.
So my questions are:

Is it always possible to perform such a normalization?
How would you do this in practice when you do not know $u(t)$, which is obviously the case as otherwise you wouldn't need to use the above expression?

A: Sure, it's possible to perform this normalization except in the case that the right eigenvector corresponding to eigenvalue $\lambda$ becomes orthogonal to $u(0)$, which is presumably why they consider only small $t$.
Think about it this way: the eigenvector corresponding to a given eigenvalue is only defined up to a complex constant, and it is not clear how to differentiate $u(t)$ if you allow its image to be an entire one-dimensional subspace, rather than a vector. So instead of considering all possible rescalings of the eigenvector, Magnus and Neudecker are selecting one particular representative element in the equivalence class of vectors which have $\lambda$ as an eigenvalue; this representative element sweeps out a curve in $\mathbb{C}^n$ as $t$ varies and can be differentiated.
In the real case, the natural normalization is to require $\|u(t)\|^2=1$, but obviously this does not work in the complex domain.
Finally I'm not sure what the "this" is you're asking about in the second part of the question: the formula you've listed only requires knowing $u(0$), not $u(t)$ for other $t$, but in any case performing the normalization is easy: if $v$ is an eigenvector with eigenvalue $\lambda$ at some $t$, you normalize it by computing
$$u(t) = \frac{v}{\langle v, u(0)\rangle}.$$


text:
Q: $\int \frac{1}{x(x+1)...(x+n)}dx$ I have not managed to evaluate the integral. I feel the idea is just split the integral into a sum of integrals
$$\int \frac{1}{x(x+1)...(x+n)}dx = \int \left(\frac{A_1}{x} + \frac{A_2}{x+1} +... +\frac{A_n}{x+n} \right) dx$$
So, technically, the main problem is to determine the coefficients in the numerators of these fractions. Hhm, it has occurred to me that I might bypass the system of $n$ equations just putting $x = 0$, $x = - 1$,..., $x = - n$ after multipling the whole expression by $x(x+1)...(x+n)$. The idea can be of help to solve the risen problem.
Another idea is just to decompose the fraction by representing the numerator of the initial fraction, which is 1, as an expression considered to be suitable to attain the objective. For example,
$$ 1 = x + 1 - (x + 2) + (x + 3) - (x + 4) +... $$
I might attempt to adopt the idea but there is a nice trick that solves the problem? I came across the integral when searching for the competition problems on integration.
When trying to apply "brutal force" method, I got many brackets and equations afterwards. Hence, there must be more cunning technique.

A: Your idea is correct.
This is the easiest case where you can do partial fraction decomposition since the polynomial in the denominator splits as distinct linear factors. In this case, you can apply the Heaviside cover-up method.


text:
Q: Changing colorbar numbers I have a dataset which has a scatter3 plot with a matrix for colourspace ranging between -2.5 and 0. The blue part of the colourspace is associated with the values that are lower therefore the -2.5. This is OK.
I would like to be able to edit the colorbar so that I can change which value is associated with the ends of the colourbar manually. So that only on the figure I can set -2.5 to be 0 and 0 to be 2.5. The changes need to be cosmetic only.
Is there a way of doing this using the caxis command?
Thanks!

A: Here is an example in the same kind,
set cbtics ("-2.5" -2.5, "-1.5" -1.5, "0" 0, "1.5" 1.5, "2.5" 2.5)
set palette defined (-2.5 "color1", -1.5 "color1", -1.5 "color2", 0 "color2", 0 "color3", ...)
plot your data

Note:- each color will repeat twice one for starting and another for ending.


text:
Q: Help to identify part I'm trying to repair a broken baby monitor and found an interesting looking part. It looks like an thermocouple but I'm not sure. Do you have any ideas?

See board picture.

A: To me, this looks more like a thermistor than a thermocouple.
Can you measure the resistance across this part?  If it's zero Ohms (short), then it's a thermocouple.  If it's on the order of 10kΩ at room temperature, then it's a thermistor.
What materials are the wires made of?  If they are both copper, then it's certainly not a thermocouple.
Can you describe what was this connected to inside of the unit?  If it's connected directly to the microcontroller, then it's probably a thermistor.  Thermocouples have weaker signal than thermistors, so they require more signal conditioning.


text:
Q: Chrome/jQuery Uncaught RangeError: Maximum call stack size exceeded (Function Loop) so i'm quite puzzled how this is happening but my jQuery is somehow causing some kind of conflict and racking up the memory use to over 1.2gbs for that one tab.
<script>
function homeFader(){
        setTimeout(function() {
            $("#homeBannerContainer").fadeOut(3000);
            $(".bannerRightUnicef").animate({marginLeft:"457px"},0);
        }, 3000);

        setTimeout(function() {
            $("#homeBannerContainerTwo").fadeOut(3000);
        }, 8000);

        setTimeout(function() {
            $(".bannerRightUnicef").animate({marginLeft:"0px"},1000);
        }, 9000);

        setTimeout(function() {
            $("#homeBannerContainer").fadeIn(3000,function() {
                $("#homeBannerContainerTwo").css("display","block");
            });
        }, 13000);

        setInterval(function() { homeFader(); },15000);

}

$(document).ready(function() {
    homeFader();
});

</script>

Any solution to this?
Greatly appreciated
~Matt

A: As mentioned in the comments use setTimeout() in the homeFader instead of setInterval
function homeFader() {
    setTimeout(function () {
        $("#homeBannerContainer").fadeOut(3000);
        $(".bannerRightUnicef").animate({
            marginLeft: "457px"
        }, 0);
    }, 3000);

    setTimeout(function () {
        $("#homeBannerContainerTwo").fadeOut(3000);
    }, 8000);

    setTimeout(function () {
        $(".bannerRightUnicef").animate({
            marginLeft: "0px"
        }, 1000);
    }, 9000);

    setTimeout(function () {
        $("#homeBannerContainer").fadeIn(3000, function () {
            $("#homeBannerContainerTwo").css("display", "block");
        });
    }, 13000);

    setTimeout(homeFader, 15000);
}

$(document).ready(function () {
    homeFader();
});

or call setInterval like
function homeFader() {
    setTimeout(function () {
        $("#homeBannerContainer").fadeOut(3000);
        $(".bannerRightUnicef").animate({
            marginLeft: "457px"
        }, 0);
    }, 3000);

    setTimeout(function () {
        $("#homeBannerContainerTwo").fadeOut(3000);
    }, 8000);

    setTimeout(function () {
        $(".bannerRightUnicef").animate({
            marginLeft: "0px"
        }, 1000);
    }, 9000);

    setTimeout(function () {
        $("#homeBannerContainer").fadeIn(3000, function () {
            $("#homeBannerContainerTwo").css("display", "block");
        });
    }, 13000);
}

$(document).ready(function () {
    homeFader();
    setInterval(homeFader, 15000);
});


text:
Q: Different Uint8Array after conversion I'm trying some stuff with the new WebCrypto API. The window.crypto.subtle.encrypt function outputs the encrypted text as ArrayBuffer - but later on I want to send this output to my server, so I need it as a string.
But now I'm facing some crazy problem regarding the conversion:
console.log(encrypted); //ArrayBuffer { byteLength: 28 } (sample output from encryption function)
var encryptedAsUint8 = new Uint8Array(encrypted);
console.log(encryptedAsUint8); //Uint8Array [ 25, 235, 161, 121, 221, 61, 132, 15, 161, 17...

var decoded = new TextDecoder("utf-8").decode(encrypted);
console.log(decoded); //�y�=��ͨ˫~���@��UcQ�
var decoded64 = btoa(encodeURIComponent(decoded));
console.log(decoded64); //JTE5JUVGJUJGJUJEeSVFRiVCRiVCRCUzRCVFRiVCRiVCRCUwRiVFRiVCRiVCRCUxMSVDRCVBOCVDQiVBQn4lRUYlQkYlQkQlRUYlQkYlQkQlMDIlN0YlRUYlQkYlQkQlNDAlRUYlQkYlQkQlRUYlQkYlQkRVY1ElRUYlQkYlQkQ=
var encodedAgain = decodeURIComponent(atob(decoded64));
console.log(encodedAgain); //�y�=��ͨ˫~���@��UcQ�
console.log(decoded === encodedAgain); //true - AS YOU CAN SEE, UNTIL THIS POINT THE CONTENT SEEMS TO BE THE SAME - but now:

var backToUint8 = new Uint8Array(new TextEncoder("utf-8").encode(encodedAgain));
console.log(backToUint8 === encrypted); //false ???????
console.log(backToUint8); //Uint8Array [ 25, 239, 191, 189, 121, 239, 191, 189, 61, 239,... ---> WHY IS THE ARRAY NOW A DIFFERENT ONE?

Thanks for any helpful advice in advance! Sorry for my bad English.


text:
Q: Can the wrong power cord harm a desktop computer Can the wrong power cord harm a desktop computer - my daughter used a TV power cord and the computer will not turn on. Thanks!

A: If you are only talking about the passive part of the cable, i.e. this one:

(or similar designs), then no, or at least vanishingly unlikely.
If you are talking about the transformer portion, i.e. this part:

then perhaps, but the connector should most likely not fit if there would be a problem (but that is not fail-safe). These external adapters are more or less exclusively used for laptops, but there are desktop computers that use them. Thought I'd mention it since we don't know exactly what kind of desktop computer (or TV, or cord) it concerns.
With "perhaps" I mean that if the voltage rating doesn't match what the laptop wants, then it will not work, but if it goes as far as damaging it or if it has safeguards protecting it against things like that is difficult to say without more information. The first thing that would stop functioning would probably be the adapter in itself.


text:
Q: Accented column names, introspection and mapping I would like to access a legacy MSSQL database using SQLAlchemy. With basic schema inspection I could already list the columns of the tables I'm interested in. Unfortunately, these column names sometimes contain accented letters (e.g. "Magánszemély", "LevelezésiCímIrányítószám").
My only requirement is to be able to query this DB.
I've listed some database names for you using the following commands
def inspect_komplex_table():
    table = Table('D_Allomanylista_Komplex_V', meta, autoload=True, autoload_with=engine)
    return table

def get_columns():
    keys = inspect_komplex_table().columns.keys()
    keys.sort()
    txt = '\n'.join(keys)
    open('column_names.txt', 'w').write(txt.encode('utf8'))

This gives a (long) list in the column_names.txt file with lines:
...
JutÉrvKezd
KEZDET
KTVSZAM
KamaraiTagszám
Képviselők
Lejarat
LevelezésiCímIrányítószám
LevelezésiCímUtca
LevelezésiCímVáros
...

I've tried to create a basic mapping without the accented columns first
class BiztositasokModel(object):

    def __init__(self, UgyfKod):
        self.ugyfelkod = UgyfKod

where UgyfKod is one the columns from the introspection, but
mapper(BiztositasokModel, inspect_komplex_table())

fails with UnicodeEncodeError
Could someone give me an idea on how to handle such a DB?

A: I've managed to find two answers, one using the declarative syntax, the other using the classical mapping.
Both implement a way to change the default naming scheme of the mapping columns to Python object properties.
The classical mapping answer is: SQLAlchemy mapping table with non-ascii columns to class
The answer using a declarative syntax: http://docs.sqlalchemy.org/en/latest/orm/mapper_config.html#automating-column-naming-schemes-from-reflected-tables


text:
Q: Count the number of occurences of a character in a string - BigQuery We would like to run a query that returns no of character in the given string if i have a string say : Baitul Sharaf, 105 Hill Road, Bandra (west), Mumbai
I want to count no of ',' in the above string (In above case 3)
see the reference for my question Count the number of occurrences of a character in a string in Javascript
I want to achieve the same in BigQuery

A: SELECT LENGTH(col) - LENGTH(REGEXP_REPLACE(col, ',', '')) FROM TableName


text:
Q: Radius of an arc in java // The class for drawing arcs on a panel
1  class ArcsPanel extends JPanel {
2   @Override
3   protected void paintComponent(Graphics g) {
4     super.paintComponent(g);
5
6     int xCenter = getWidth() / 2;
7     int yCenter = getHeight() / 2;
8     int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);
9
10    int x = xCenter - radius;
11    int y = yCenter - radius;
12
13    g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
14    g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
15    g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
16    g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
17  }
18}

i do not understand line 8. Explanation of the formula of getting radius. From where does he get 0.4 in radius formula? i did not find the formula.
finding the radius of an arc is different.
I found it from " Introduction to Java Programming, Comprehensive Version (9th Edition); Listing 13.4 example; page : 489 (522 / 1947) "

A: The 0.4 seems to be a relative value, meaning "the corner radius is 40% of the lesser of width and height".
EDIT: This is an perfect example, why uncommented code and magic constants are bad. Normally, you would use a variable or a parameter instead of a magic constant.


text:
Q: macOS Ventura Xcode 14, unable to use self signed provisioning profile, "Profile is missing the required UUID property." I am using a self signed provisioning profile, made with this tutorial: https://dkimitsa.github.io/2018/01/04/ios-homemade-provision-profile/
This was working great until i've updated to macOS Ventura (macOS 13.0), it has removed my self made provisioning profile and does not let me install it again.


text:
Q: start_workspaces() only accepts keyword arguments I am trying to write a Python code in Lambda function which will start the stopped workspaces when the alarm triggers. The response type is dict.
But I am getting the error. Below is my code and error.
import json
import boto3

client = boto3.client('workspaces')

def lambda_handler(event, context):
    response = client.describe_workspaces(
        DirectoryId='d-966714f114'
    )

    #print(response)

    print("hello")

    for i in response['Workspaces']:
        if(i['State']== 'STOPPED'):
            print(i['WorkspaceId'])
            client.start_workspaces(i['WorkspaceId'])

{
    "errorMessage": "start_workspaces() only accepts keyword arguments.",
    "errorType": "TypeError",
    "stackTrace": [
    "  File \"/var/task/lambda_function.py\", line 21, in lambda_handler\n    client.start_workspaces(i)\n",
    "  File \"/var/runtime/botocore/client.py\", line 354, in _api_call\n    raise TypeError(\n"
    ]
}

A: If you look at the call's documentation, it says that it expects keyword StartWorkspaceRequests, which is in itself a list of dicts:
{
    'WorkspaceId': 'string'
},

The call doesn't accept arguments (just a value being passed without corresponding keyword). You need to adapt your call to conform to the format expected by boto3.
import json
import boto3

client = boto3.client('workspaces')

def lambda_handler(event, context):
    response = client.describe_workspaces(
        DirectoryId='d-966714f114'
    )

    workspaces_to_start = []

    for i in response['Workspaces']:
        if(i['State']== 'STOPPED'):
            workspaces_to_start.append({'WorkspaceId': i['WorkspaceId']})

    if workspaces_to_start:
        client.start_workspaces(StartWorkspaceRequests=workspaces_to_start)


text:
Q: Method of characteristics for first order linear P.D.Es of degree k I understand that the method of characteristics can be used to obtain analytical solutions of any first order linear P.D.E with constant or variable coefficients. But in all the examples and proofs that I've seen, the equations involved are all of degree $1$. And as far as I've tried, I can't seem to make this method work for equations of a higher degree.
Can the method of characteristics be tweaked in some way for solving equations like $a(u_x)^2 + b(u_y)^2 +cu =0$? If not, how does one solve such equations?


text:
Q: Getting column number from td Writing an extension for tablesorter.. though its my first attempt at extending any js. I have a number of <select>s within a row of <td>s & need to know the column this td sits in.
When a value is changed in any of these selects e.g.
$('select').change(function(){

});

I need to get hold of the column this select is sitting in to set col for:
('tr.result > td:nth-child('+col+')').each(function(){

Is there a way I can get this from the td select is in?!?
--
solution for my specific problem was:
$('select').change(function(){

    td  = $(this).parent('td');

    col = $(td).parent().children().index(td);

});

A:
The cellIndex property returns the position of a cell in the cells collection of a table row.
  w3schools

 td.cellIndex

demo

A: You can use the index() function.
col = $(this).parent().children().index($(this));


text:
Q: how to create installer for my application in linux I created a java application(jar files) and want to install package for my application with following items:

*

*jre1.7.9

*mysql

*my fonts

how to create a installer for my app Which is available on all Linux distributions?

A: may be you can execute a .jar file from the terminal. this link can be helpful to you.

A: Download izpack from
run IzPack-install.jar. there should be jdk installed on your pc.
After installation open folder where it is installed.
See this tutorial.


text:
Q: PubNub issue in node 12 Has anyone tried running pubnub sdk in node 12.x?
On their docs, found that it supports till node 8. Link - https://www.pubnub.com/docs/web-javascript/supported-platforms
Does anyone have any updates whether they are going to add support for 12 soon or any possible workaround?

A: PubNub Node Versions Support
Thanks for bringing this to our attention. We are building in travis on node 12 with success, we just need to update the supported versions. We will likely update it when when do a new release (4.27.2) today.


text:
Q: Fragments inside a Gridview in Android Is it possible to accommodate a Fragments view inside a Gridview.  I m unable to find any support with regards to this in the internet.
My basic requirement is i m unaware how many fragments i would be in need i to display wherein the number of fragments would be decided dynamically. Each fragment would contain a separate webviews inside it.
Any sample code would be of great help

A: Fragment doesn't inherited from View. So its impossible to populate grid with fragments. GridView needs in BaseAdapter which should implement View getView method.
You should write your custom views instead of fragments.

A: Fragment is independent from view even also from activity .it has life-cycle .I mean you cant make fragment inside GridView. Either you have to make your own custom view by extending gridview .or Use only fragment. Use add and replace to do more ...if you want to play with fragment.

A: You cannot use GridVew but you have a GridLayout, where fragments can be put


text:
Q: BigQuery standart SQL - how to calculate 2 timestamp2 difference in minutes I'm using BigQuery standart SQL and i need to find the difference between 2 timestamps, in minutes.
For example:
Timestamp1 = '2016-10-10 09:40:00'   |
Timestamp2 = '2016-10-10 09:50:00'
I want to return the difference:
Timestamp2-Timestamp1 = 10
I found how to do it with Legacy SQL, but it doesn't help:
https://cloud.google.com/bigquery/query-reference#datediff
Thank you !

A: check for TIMESTAMP_DIFF function
SELECT
  TIMESTAMP "2016-10-10 09:50:00" as first_timestamp,
  TIMESTAMP "2016-10-10 09:40:00" as second_timestamp,
  TIMESTAMP_DIFF(TIMESTAMP "2016-10-10 09:50:00",
    TIMESTAMP "2016-10-10 09:40:00", MINUTE) AS minutes;


text:
Q: Asp.net Gridview - Why Are DataRowBound changes Lost on sort? I am making conditional formatting changes to the data in my gridview using a RowDataBound event:
    void gvReg_RowDataBound(object sender, GridViewRowEventArgs e)
    {

       if (e.Row.RowType == DataControlRowType.DataRow)
       {

          DateTime lastUpdate DateTime.Parse(DataBinder.Eval   (e.Row.DataItem, "LAST_UPDATE");

          if (lastUpdate < DateTime.Today.AddMonths(-1))
          {

             Hyperlink hypLastUpdate = (Hyperlink)e.Row.FindControl("hypLastUpdate";
             hypLastUpdate.CssClass = "Error";
             hypLastUpdate.NavigateUrl = "http://www.someExampleErrorPage.com";

          }

       }

    }

This works, and sets the proper CssClass to the hyperlink (which makes it a jarring shade of bold red), but once the gridview is sorted (via the user clicking a column heading) the css class is reset on hypLastUpdate and it loses both it's style and associated NavigateUrl property.
The control hypLastUpdate is contained in a template field in a gridview, and it's text value is databound to a field called "LAST_UPDATE".
Is this a planned behavior (is sorting supposed to break the conditional formatting done in RowDataBound events?) or is there something I can check to make sure I am not doing something incorrectly?
I am not using the DataBind method anywhere in the code behind, and viewstate is turned on for the gridview in question.
--EDIT--
It ended up being a mistake in event handling.
I was doing:
gvReg.Sorted += {SomeEventHandler}

Inside of the page load event, but only when it wasn't a postback.  This function called gvReg.DataBind after the grid view was sorted.  I removed the handler wire up and instead added the event handler function to the OnSorted event.  I guess assigned delegates to a gridview are not saved in ViewState between callbacks?

A: Hi here is a quick example of what I meant on my comment. This is the only way i could think of it:
    protected void gvReg_Sorting(object sender, GridViewSortEventArgs e)
    {
        GridView gridView = (GridView)sender;

        if (e.SortExpression.Length > 0)
        {
            foreach (DataControlField field in gridView.Columns)
            {
                if (field.SortExpression == e.SortExpression)
                {
                    cellIndex = gridView.Columns.IndexOf(field);
                    break;
                }
            }

            if (pSortExpression != e.SortExpression)
            {
                pSortDirection = SortDirection.Ascending;
            }
            else
            {
                pSortDirection = (pSortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending);
            }
            pSortExpression = e.SortExpression;
        }

        //Retrieve the table from the database
        pSortOrder = pSortDirection == SortDirection.Ascending ? "ASC" : "DESC";
        List<Partners> partnerList = GetPartnerList();

        gvReg.DataSource = partnerList;
        gvReg.DataBind();

    }


text:
Q: How to merge and replace objects from two arrays based on a key in javascript? I have two array object(arrayList1,arrayList2). Just I am trying to merge those two arrays into one array object.
The following terms I used.

*

*Both array merged into one array based on key-name is type.

*arrayList2 values will be overwrite the arrayList1.

*I Got the expected output but I am worying to do with efficient and performance way..

Can someone please simplify my code..
Note :

*

*It would be great if using Array.reduce function and without use any plugin/library..

*I added the smaple input for understanding. The element order will be change and size of both array's will change.

const arrayList1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];

const arrayList2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];

result = arrayList2.reduce(function (arr1, arr2) {
  let isMatchFound = false;
  arr1.forEach(function (list) {
    if (arr2.type == list.type) {
      list = Object.assign(list, arr2);
      isMatchFound = true;
    }
  });
  if (!isMatchFound) {
    arr1.push(arr2);
  }
  return arr1;
}, arrayList1);

console.log('result', JSON.stringify(result));

A: You may also use .reduce() and Object.values() methods to get the desired output:

const arrayList1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];

const arrayList2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];

const result = Object.values(
   [].concat(arrayList1, arrayList2)
     .reduce((r, c) => (r[c.type] = Object.assign((r[c.type] || {}), c), r), {})
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You could do something like this using reduce and Object.values

const array1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];

const array2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];

const mapped = array1.reduce((a,t)=> (a[t.type] = t, a), {}),
      mapped2 = array2.reduce((a,t)=> (a[t.type] = t, a), {})

console.log(Object.values({...mapped, ...mapped2}))

A: If you just wanted to make your code smaller:

const arrayList1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];

const arrayList2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];

result = arrayList2.reduce(function(arr1, arr2) {
  if (arr1.find(({ type }) => type == arr2.type)) {
    arr1[arr1.indexOf(arr1.find(({ type }) => type == arr2.type))] = Object.assign(arr1.find(({ type }) => type == arr2.type), arr2);
    arr1.push(arr2);
  }
  return arr1;
}, arrayList1);

console.log('result', JSON.stringify(result));

A: If you dont exactly need arrayList1 before arrayList2, you can use this one liner simple approach.
What I have done is I have destructured all elements arrayList2 and only those elements of arrayList1 whose key does not exist in arrayList1.
P.S. the problem with reduce is you have to reduce the largest array otherwise you will miss out the elements of bigger Array.

const arrayList1 = [
    { type: "A", any: 11, other: "ab", props: "1" },
    { type: "B", any: 22, other: "bc", props: "2" }, // same type
    { type: "C", any: 33, other: "df", props: "3" }
];

const arrayList2 = [
    { type: "D", any: 44, other: "aa", props: "11" },
    { type: "B", any: 22, other: "bb", props: "2----2" , x: 10}, // same type
    { type: "E", any: 44, other: "cc", props: "33" }
];
const output = [...arrayList2, ...arrayList1.filter(el1 => !arrayList2.some(el2 => el2.type === el1.type))]
//[].concat(arrayList2, arrayList1.filter(el1 => !arrayList2.some(el2 => el2.type === el1.type)))

console.log(output)


text:
Q: CSS selector to select last TD which does not have 'hide' class in its row I have a table row with TD , each TD element has 'm-rowcell' class and some cells are hidden by using 'm-hide' class.
I need to select last TD element Which is not have 'm-hide' class by using only CSS.

.m-hide {
  display: none;
}
.m-rowcell {
  border: 1px solid;
}
tr td:last-child { /*visible last child*/
  background: #FFAA33;
}

    Header 1
    Header 2
    Header 3

    content 1
    content 2
    content 3

    content 1
    content 2
    content 3

    content 1
    content 2
    content 3

How to do this?
JSfiddle Demo

A: EDITED AFTER QUESTION REPHRASE
You can't do that with only css.
CSS can reach last element of its parent, last element of its type but can't go back to its previous sibling without affecting all others.
You can do that by cycling in javascript/jquery or just adding a specific class to those td you want select.


text:
Q: Creating a menu using Grails How can I build a menu-like selection bar in Linux using Grails? Is there any plugin that can help do this?

A: This one?
GrailsUI (GUI) is a plugin that provides an extensive tag library of rich ajax components based on the Yahoo! UI (YUI) JavaScript library and a YUI extension called the Bubbling Library. It has been designed for ease-of-use as well as configurability.
http://grails.org/plugin/grails-ui

A: You could also use the Grails Navigation plugin.


text:
Q: Extracting multiple values of raster to polygons using ArcGIS for Desktop? I was hoping I could get some help on how to extract information from a land use raster using polygons. I have a layer with 157 polygons and a land use raster with multiple land use categories for the whole region. I need to calculate the area for each land use type in each of the polygons (either the area or the number of pixels). I already extracted the land use information using my polygons as a mask, but I have been unable to get the counts/area for each land use category PER polygon.
I have tried all the zonal and extraction tools, but I either get pixel counts of each land use in the whole layer (not counts per polygon) or I get the overall area for each polygon without any detail on the area for each land use category per polygon.
Could someone point me in the right direction please?

A: A thematic/categorical dataset such as landuse would technically be appropriate for a polygon feature class rather than a raster.  So, one solution would be to convert your land use raster to a vector layer, and then perform a spatial join that would result in an attribute table with a record for each polygon--land use combination.  Another option is to use the Intersect tool on the two polygon layers.


text:
Q: Getting rid of characters when doing gf in vim I am using vim for coding. When I have something like the following:
SomeModule->actualMethod() if I take the cursor to SomeModule and I do a gf I get a complaint that SomeModule- does not exist in the path.
How can I get rid of the - so that the SomeModule file opens?

A: What Vim considers part of a filename is controlled by the 'isfname' option. You need to remove the dash from it for your example to work:
:set isfname-=-

Note that when your SomeModule file has a file extension, you also need to add it to 'suffixesadd'.