text:
Q: MVC 2 UpdateModel on Interface, Should ModelBinderAttribute be ignored? I have forms posting data from instances of a particular abstract class:
public abstract class IRestriction
{
    public string Name {get; set;}
    public abstract IModelBinder GetBinder();
}

The concrete type and PartialView are determined at runtime:
IRestriction restriction = (IRestriction)Activator.CreateInstance(Type.GetType(restriction.restriction_class));

The appropriate partial view is then rendered correctly.
When the form is sent back the type is inferred correctly and activated the same way.
However, I haven't been able to get UpdateModel to bind to the concrete implementation.
How do I get the Model to bind to the concrete type instead of the interface?
Things I've tried:
I've set the ModelBinderAttribute on the concrete class but it is being ignored.
[ModelBinder(typeof(MyCustomModelBinder))]
public class ConcreteRestriction : IRestriction

I've cleared all the ModelBinders and added only the binder from the interface.
Binders.Clear();
Binders.Add(item.GetType(), item.GetBinder());

None of these is working.
Whats the best way to accomplish what I'm trying to do?
Is ModelBinderAttribute being ignored in error?
** ----------------------UPDATE----------------------**
Here is a solution for anyone else struggling with the same issue who happens to run across this.
The following class inherits Controller. Inherit it and call UpdateModelDynamic()/TryUpdateModelDynamic()
public class DynamicTypeController : Controller
{
    internal static bool IsPropertyAllowed(string propertyName, string[] includeProperties, string[] excludeProperties)
    {
        // We allow a property to be bound if its both in the include list AND not in the exclude list.
        // An empty include list implies all properties are allowed.
        // An empty exclude list implies no properties are disallowed.
        bool includeProperty = (includeProperties == null) || (includeProperties.Length == 0) || includeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);
        bool excludeProperty = (excludeProperties != null) && excludeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);
        return includeProperty && !excludeProperty;
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model) where TModel : class
    {
        return TryUpdateModelDynamic(model, null, null, null, ValueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, string prefix) where TModel : class
    {
        return TryUpdateModelDynamic(model, prefix, null, null, ValueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, string[] includeProperties) where TModel : class
    {
        return TryUpdateModelDynamic(model, null, includeProperties, null, ValueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties) where TModel : class
    {
        return TryUpdateModelDynamic(model, prefix, includeProperties, null, ValueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) where TModel : class
    {
        return TryUpdateModelDynamic(model, prefix, includeProperties, excludeProperties, ValueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, IValueProvider valueProvider) where TModel : class
    {
        return TryUpdateModelDynamic(model, null, null, null, valueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, string prefix, IValueProvider valueProvider) where TModel : class
    {
        return TryUpdateModelDynamic(model, prefix, null, null, valueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, string[] includeProperties, IValueProvider valueProvider) where TModel : class
    {
        return TryUpdateModelDynamic(model, null, includeProperties, null, valueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties, IValueProvider valueProvider) where TModel : class
    {
        return TryUpdateModelDynamic(model, prefix, includeProperties, null, valueProvider);
    }

    protected internal bool TryUpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider) where TModel : class
    {
        if (model == null)
        {
            throw new ArgumentNullException("model");
        }
        if (valueProvider == null)
        {
            throw new ArgumentNullException("valueProvider");
        }

        Predicate<string> propertyFilter = propertyName => IsPropertyAllowed(propertyName, includeProperties, excludeProperties);
        IModelBinder binder = Binders.GetBinder(model.GetType());

        ModelBindingContext bindingContext = new ModelBindingContext()
        {
            ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
            ModelName = prefix,
            ModelState = ModelState,
            PropertyFilter = propertyFilter,
            ValueProvider = valueProvider
        };
        binder.BindModel(ControllerContext, bindingContext);
        return ModelState.IsValid;
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model) where TModel : class
    {
        UpdateModelDynamic(model, null, null, null, ValueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, string prefix) where TModel : class
    {
        UpdateModelDynamic(model, prefix, null, null, ValueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, string[] includeProperties) where TModel : class
    {
        UpdateModelDynamic(model, null, includeProperties, null, ValueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties) where TModel : class
    {
        UpdateModelDynamic(model, prefix, includeProperties, null, ValueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties) where TModel : class
    {
        UpdateModelDynamic(model, prefix, includeProperties, excludeProperties, ValueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, IValueProvider valueProvider) where TModel : class
    {
        UpdateModelDynamic(model, null, null, null, valueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, string prefix, IValueProvider valueProvider) where TModel : class
    {
        UpdateModelDynamic(model, prefix, null, null, valueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, string[] includeProperties, IValueProvider valueProvider) where TModel : class
    {
        UpdateModelDynamic(model, null, includeProperties, null, valueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties, IValueProvider valueProvider) where TModel : class
    {
        UpdateModelDynamic(model, prefix, includeProperties, null, valueProvider);
    }

    protected internal void UpdateModelDynamic<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider) where TModel : class
    {
        bool success = TryUpdateModelDynamic(model, prefix, includeProperties, excludeProperties, valueProvider);
        if (!success)
        {
            string message = String.Format("The model of type '{0}' could not be updated.", model.GetType().FullName);
            throw new InvalidOperationException(message);
        }
    }

}

A: I think it's a bug, but the ASP.NET MVC team disagrees. Model binding looks at the static, compile-time type of the model. I don't like it, but that's how it is.


text:
Q: how to make this static public static Bitmap bmp;
bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.nehe);

the error for above code "Syntax error on token ";", , expected" I already put a semi colon after bmp but still the error occurs
here is the full code:
public class CustomActivity extends AndARActivity {

ARToolkit artoolkit;
CustomObject someObject;
CustomObject1 someObject1;

public static Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.nehe);

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    CustomRenderer renderer = new CustomRenderer();

    super.setNonARRenderer(renderer);

    try {
        //register a object for each marker type
        artoolkit = super.getArtoolkit();

        someObject = new CustomObject
            ("test", "androidpirate.patt", 80.0, new double[]{0,0});
        artoolkit.registerARObject(someObject);

        someObject = new CustomObject
        ("test", "andson.patt", 80.0, new double[]{0,0});
        artoolkit.registerARObject(someObject);

        someObject1 = new CustomObject1("test","andrev.patt", 80.0, new double[]{0,0});
        artoolkit.registerARObject(someObject1);

        someObject1 = new CustomObject1("test","androidpat.patt", 80.0, new double[]{0,0});
        artoolkit.registerARObject(someObject1);

    } catch (AndARException ex){
        //handle the exception, that means: show the user what happened
        System.out.println("");
    }
    startPreview();
}

@Override
public void uncaughtException(Thread thread, Throwable ex) {
    Log.e("AndAR EXCEPTION", ex.getMessage());
    finish();
}
}

A: public declarations can be used only for class variables not for function variables

A: You are calling "this" in a static context, "this" refers to the class instance object, therefore using it in a static manner is not a valid Java syntax. Additionally, I don't think "this.getResources()" would return anything but null until the time onCreate(Bundle) method is called.
You should do something like:
public static Bitmap bmp;

public void onCreate(Bundle savedInstanceState) {
    if(bmp!=null) {
        BitmapFactory.decodeResource(this.getResources(), R.drawable.nehe);
    }
...other code here

A: public static Bitmap bmp =
    BitmapFactory.decodeResource(this.getResources(), R.drawable.nehe);

or
public static Bitmap bmp;

static {
    bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.nehe);
}

A: If you are writing those statements in a method, then public is not a valid access modifier for local variables.
If you are writing those statements outside a method within a class, then those statements should be combined as follows:
public Bitmap bmp =
    BitmapFactory.decodeResource(this.getResources(), R.drawable.nehe);

This is because, only initializers are allowed outside methods or blocks, but not assignment statements like your second statement.
Since you seem to have a dependency on the return value of getResources() member method, bmp cannot be static. Also, it is better to initialize bmp only when you are sure that the return value of getResources() method is meaningful. You should show more code from your class to get better help w.r.t this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problems defining methods I try define a private method i have:
unit FormENP;

interface

uses
  ....

type
  TENPDataEntry = class(TForm)
  ........
  private
    { Private declarations }
    function getLastIdMuestra(): integer;

  public
    { Public declarations }
  end;

var
  ENPDataEntry: TENPDataEntry;

implementation

{$R *.dfm}
{ Devuelve el id de la última muestra insertada en <MUESTRA> }
function getLastIdMuestra(): integer;
var
  query: TIBQuery;
  id: integer;
begin
  query := TIBQuery.Create(nil);
  ....
  id := query.Fields[0].AsInteger;
  query.Destroy;
  getLastIdMuestra := id;
end;
...
End.

But the compiler says:

[DCC Error] FormENP.pas(30): E2065 Unsatisfied forward or external
  declaration: 'TENPDataEntry.getLastIdMuestra'

The line 30 is the method signature:

function getLastIdMuestra(): integer;

Im newbie in Delphi, any ideas ?. I think that the code is fine...

A: You are missed the class name in the method definition, try
function TENPDataEntry.getLastIdMuestra(): integer;


text:
Q: iOS - Is Swift bundled with the app binary or the operating system I'm curious if Swift is natively a part of the iOS 7/8/9 operating system or if the application binary carries the swift runtime with it (potentially increasing binary size)?
I'm similarly curious if this is the case for Objective-C.

A: There is a Swift runtime library embedded in the app to ensure compatibility as you can see here.

A: If your app has Swift code, you can unzip your .ipa file and explore the contents of the .app folder. You will see that the app bundle is including the Swift runtime library

So yes, it is increasing the app size by a few MB


text:
Q: How to create grid of drawing using python's turtle I made the letter "U" using turtle, but now i need to make several copies of it to form a grid of 3 rows and 4 columns. I was trying to use a nested loop, but I do not how to make the drawing move position to create the grid. it should end up something like this logo grid
def draw_U(posx, posy, color):
t = turtle.Turtle()
t.speed(10)
t.ht() #hides the turtle/pen
t.penup()
t.setposition(posx,posy)
t.pendown()
t.color(color)
t.begin_fill()#starts filling
t.forward(60)#line 1 starting at top left corner of the 'U'
t.right(90)
t.forward(25) #line 2
t.right(90)
t.forward(8) #line 3
t.left(90)
t.forward(138)#line 4
t.left(45)
t.forward(13) #line 5
t.left(45)
t.forward(75) #line 6
t.left(45)
t.forward(13) #line 7
t.left(45)
t.forward(138) #line 8
t.left(90)
t.forward(8) #line 9
t.right(90)
t.forward(25) #line 10
t.right(90)
t.forward(60) #line 11
t.right(90)
t.forward(25) #line 12
t.right(90)
t.forward(8) #line 13
t.left(90)
t.forward(163)#line 14
t.right(45)
t.forward(35) #line 15
t.right(45)
t.forward(133) #line 16
t.right(45)
t.forward(35) #line 17
t.right(45)
t.forward(163) #line 18
t.left(90)
t.forward(8) #line 19
t.right(90)
t.forward(25) #line 20
t.end_fill() #completely fills shape

def draw_Grid(posx, posy, rows, cols):
t= turtle.Turtle()
t.ht()
for i in range(cols):
   for j in range(rows):
       print(draw_UH(posx, posy, 'red'))

draw_Grid(-300, 300, 3, 4)

A: In draw_Grid you need to use the row and column numbers to calculate the starting position for each U. But you also need to fix draw_U so that after it's finished drawing a U it puts the turtle back where it started, heading in the original direction.
Here's a repaired version of your code.
import turtle

def draw_U(t, posx, posy, color):
    t.penup()
    t.setposition(posx,posy)
    t.pendown()
    t.color(color)
    t.begin_fill()#starts filling
    t.forward(60)#line 1 starting at top left corner of the 'U'
    t.right(90)
    t.forward(25) #line 2
    t.right(90)
    t.forward(8) #line 3
    t.left(90)
    t.forward(138)#line 4
    t.left(45)
    t.forward(13) #line 5
    t.left(45)
    t.forward(75) #line 6
    t.left(45)
    t.forward(13) #line 7
    t.left(45)
    t.forward(138) #line 8
    t.left(90)
    t.forward(8) #line 9
    t.right(90)
    t.forward(25) #line 10
    t.right(90)
    t.forward(60) #line 11
    t.right(90)
    t.forward(25) #line 12
    t.right(90)
    t.forward(8) #line 13
    t.left(90)
    t.forward(163)#line 14
    t.right(45)
    t.forward(35) #line 15
    t.right(45)
    t.forward(133) #line 16
    t.right(45)
    t.forward(35) #line 17
    t.right(45)
    t.forward(163) #line 18
    t.left(90)
    t.forward(8) #line 19
    t.right(90)
    t.forward(25) #line 20
    t.end_fill() #completely fills shape

    # Reset the original direction and position
    t.right(90)
    t.penup()
    t.setposition(posx,posy)
    t.pendown()

def draw_Grid(t, ox, oy, rows, cols):
    t.ht()
    patwidth, patheight = 200, 220
    for i in range(cols):
        posx = ox + patwidth * i
        for j in range(rows):
            posy = oy + patheight * j
            draw_U(t, posx, posy, 'red')

# Make the turtle window 90% off the screen width & height
turtle.setup(width=0.9, height=0.9)
width, height = turtle.window_width(), turtle.window_height()

t = turtle.Turtle()
t.speed(10)
t.ht() #hides the turtle/pen

#draw_U(t, 0, 0, 'red')
draw_Grid(t, 10-width//2, 230-height//2, 3, 4)

turtle.done()

A: This seems like a situation where stamping would be more efficient than drawing:
from turtle import Turtle, Screen

BORDER = 20
LETTER_WIDTH, LETTER_HEIGHT = 200 + BORDER, 210 + BORDER
COLUMNS, ROWS = 4, 3

def draw_U(t):
    t.forward(60)  # line 1 starting at top left corner of the 'U'
    t.right(90)
    t.forward(25)  # line 2
    t.right(90)
    t.forward(8)  # line 3
    t.left(90)
    t.forward(138)  # line 4
    t.left(45)
    t.forward(13)  # line 5
    t.left(45)
    t.forward(75)  # line 6
    t.left(45)
    t.forward(13)  # line 7
    t.left(45)
    t.forward(138)  # line 8
    t.left(90)
    t.forward(8)  # line 9
    t.right(90)
    t.forward(25)  # line 10
    t.right(90)
    t.forward(60)  # line 11
    t.right(90)
    t.forward(25)  # line 12
    t.right(90)
    t.forward(8)  # line 13
    t.left(90)
    t.forward(163)  # line 14
    t.right(45)
    t.forward(35)  # line 15
    t.right(45)
    t.forward(133)  # line 16
    t.right(45)
    t.forward(35)  # line 17
    t.right(45)
    t.forward(163)  # line 18
    t.left(90)
    t.forward(8)  # line 19
    t.right(90)
    t.forward(25)  # line 20

def stamp_Grid(turtle, x, y, rows, cols):
    for c in range(cols):
        turtle.setx(x + LETTER_WIDTH * c)

        for r in range(*((0, rows) if c % 2 == 0 else (rows - 1, -1, -1))):
            turtle.sety(y + LETTER_HEIGHT * r)
            turtle.stamp()

screen = Screen()
screen.setup(COLUMNS * LETTER_WIDTH, ROWS * LETTER_HEIGHT)
screen.setworldcoordinates(0, 0, screen.window_width(), screen.window_height())

turtle = Turtle(visible=False)
turtle.speed('fastest')
turtle.penup()

turtle.setheading(90)
turtle.begin_poly()
draw_U(turtle)
turtle.end_poly()

screen.register_shape('U', turtle.get_poly())

turtle.reset()
turtle.penup()
turtle.shape('U')
turtle.color('red')

stamp_Grid(turtle, BORDER / 2, LETTER_HEIGHT - BORDER / 2, 3, 4)

turtle.hideturtle()

screen.exitonclick()

We only draw the letter once, save that drawing as a turtle cursor, switch our turtle to that cursor and start stamping out copies.


text:
Q: template for category page OpenCart 2.2.0.0 I would ask for a little help
I would like to create another template for my three categories (category ID 119 / ID 125 / ID 140).
I found one solution for version 2.2.0.0.

 find $this->response->setOutput($this->load->view('product/category', $data));
        in catalog/controller/product/category.php

        and replace it with above codes, here is:

        $config_theme = $this->config->get('config_theme') == 'theme_default' ? 'default' : $this->config->get('config_theme'); if (file_exists(DIR_TEMPLATE . $config_theme . '/template/product/category_' . $category_id . '.tpl'))   {
            $view = 'product/category_' . $category_id;
        } else {
            $view = 'product/category';
        }

$this->response->setOutput($this->load->view($view, $data));
I created category_119 however, it does not work. I tried to complete this code but nothing works

   perhaps I have to complete code by:

         * entering the name of my new template (category_bezkoszyka or category_119) = but I do not know exactly where to sign

        * enter the category ID (119/125/140) = = but I do not know exactly where to sign

        * probably enter the name of my template - although I have default - (Default (Default Store Theme)

Link to the solution:
<https://stackoverflow.com/questions/40755573/specific-template-for-category-and-product-page-in-opencart-2-2-0-0/53498989#53498989>

Information:
* opencart 2.2.0.0.
* my new temple category = category_bezkoszyka
* Id category to change = 119 / 125 / 140
* I have a standard theme: Default (Default Store Theme)

How to enter correctly, because I try but it fails.

Thank you for your help

Best Regards. Adam.


text:
Q: Responsive Web Development-CSS -mobile slider height I am trying to get my slider on my website to adjust to a different height in a mobile screen but didn't get it to work properly.
The website that i am trying to work on is www.msstoreway.com.  After having added the css-code below, i could get the desktop/laptop screen to adjust but on a mobile screen the slider height wont change at all. Can you please advise what i am doing wrong and how to get the height to increase in a mobile screen only.Thanks. See my CSS-Codes that i have added.
regards
Mark
    /* Smartphones (portrait) ----------- */
     @media only screen
     and (max-width : 320px) {
     /* Styles */
    #slider .rslides, #slider .rslides li { height: 250px; max-height:
    250px; }
    #slider .rslides img { height: 100%; max-height: 250px; }

     }

A: The plugin you are using for the slider is scaling the height/width as inline styles which is overriding your css styles.
You are able to add the !important tag which will then override the inline styles, but do note you will lose the aspect ratio scaling that the js plugin is implementing.
@media only screen and (max-width : 500px) {
    .rslides { height: 250px !important; }
    .rslides img { height: 250px !important; }
}


text:
Q: Create table of unique values from join I have two tables with various addresses. One is a table of locations we already have on file, the other is new business. The idea is that I'm joining these two tables on their co-ordinates in order to show if we have a clash between the new business and the current business.
What I have found is that in the new business we have one location that matches three locations that we already have.
When I do my simple inner join I get back 3 records when really I want to display the 4 (1 from new, 3 from current). I have tried other joins and union as well as sub queries but with no luck. I know there is a way but just can't figure it out.
SELECT *
FROM NewBusiness
INNER JOIN Live L ON N.Latitude = L.Latitude AND N.Longitude = L.Longitude

Thanks in advance

A: Maybe not the best answer (it catch duplicate rows in the same table) but still working correctly
select distinct 'oldbiz', l.id, l.latitude, l.longitude
  from Live l, NewBusiness n
 where l.latitude = n.latitude
  and l.longitude = n.longitude
union all
select distinct 'newbiz', n.id, n.latitude, n.longitude
 from Live l, NewBusiness n
where l.latitude = n.latitude
  and l.longitude = n.longitude

SQLFIDDLE

A: So I was able to get what I think you are looking for using a union. It may not be the best way to do it but it looks like it works. I made a SQL Fiddle to show it.
You can see the fiddle here: SQLFIDDLE
to test, I created two tables, Live and NewBusiness.
Created them like this
CREATE TABLE Live
    ([ID] varchar(1), [latitude] int, [longitude] int)
;

INSERT INTO Live
    ([ID], [latitude], [longitude])
VALUES
    ('a', 1, 2),
    ('b', 1, 2),
    ('c', 1, 2),
    ('d', 4, 3),
    ('e', 5, 4),
    ('k', 5, 7),
    ('l', 5, 9),
    ('M', 5, 7)
;

and
CREATE TABLE NewBusiness
    ([ID] varchar(1), [latitude] int, [longitude] int)
;

INSERT INTO NewBusiness
    ([ID], [latitude], [longitude])
VALUES
    ('f', 1, 2),
    ('g', 5, 2),
    ('h', 1, 8),
    ('i', 6, 3),
    ('z', 5, 7),
    ('y', 12, 4),
    ('x', 5, 7)
;

The query I used was
 (
   SELECT L.ID
           ,L.Latitude
           ,L.Longitude

    FROM Live L
    INNER JOIN NEWBUSINESS N
    ON L.Latitude = N.Latitude AND L.Longitude = N.Longitude
 )
 UNION
 (
   SELECT N.ID
           ,N.LATITUDE
           ,N.LONGITUDE
    FROM NEWBUSINESS N
    INNER JOIN Live L
    ON N.Latitude = L.Latitude AND N.Longitude = L.Longitude
    GROUP BY N.ID
            ,N.LATITUDE
            ,N.LONGITUDE
   )

The first part of the union gets all the things in Live that have matches in Newbusiness. The second part of the union gets all the things in Newbusiness that have matches in Live. The results are then union'd together.
Tables:
Live
ID  latitude    longitude
a   1   2
b   1   2
c   1   2
d   4   3
e   5   4
k   5   7
l   5   9
M   5   7

**NewBusiness**
ID  latitude    longitude
f   1   2
g   5   2
h   1   8
i   6   3
z   5   7
y   12  4
x   5   7

**Query Results**
ID  Latitude    Longitude
a   1   2
b   1   2
c   1   2
f   1   2
k   5   7
M   5   7
x   5   7
z   5   7

A: Does something like this give you what you need (it will count once for each record in either table that has a match in the other table):
WITH cte1
AS
(
    SELECT
        N.latitude
        , N.longitude
        , ROW_NUMBER() OVER (ORDER BY N.latitude, N.longitude) r1
    FROM NewBusiness N
)
,

cte2
AS
(
    SELECT
        N.latitude
        , N.longitude
        , ROW_NUMBER() OVER (PARTITION BY N.r1 ORDER BY N.latitude, N.longitude) r2
    FROM
        cte1 N
        JOIN Live L ON
            N.Latitude = L.Latitude
            AND N.Longitude = L.Longitude
)

SELECT
    latitude
    , longitude
    , 'NewBusiness' sourceTable
FROM cte2
WHERE r2 = 1

UNION ALL

SELECT
    latitude
    , longitude
    , sourceTable
FROM
    (
        SELECT DISTINCT
            latitude
            , longitude
            , r2
            , 'Live' sourceTable
        FROM cte2
    ) Q


text:
Q: convert the shell output to float64? i am using shell with golang to access apache log file and get some data. first i used to write output to the file directly and it was working, but now i need to get the output and use it in the program directly. and also i need to convert it to float64. i tried converting it into a string and then to float64, but it is not working?
func Mem_usage_data(j int) (Mem_predict float64, err error) {
    awkPart := fmt.Sprintf("awk '{print $%d/1024}'", j)

    out1, err := exec.Command("bash", "-c", "tail -n 1 /var/log/apache2/access.log| "+awkPart+" ").Output()
    fmt.Println("memory usage is", out1)
    s1 := string(out1)
    v1, err1 := strconv.ParseFloat(s1, 64)
    if err1 != nil {
        fmt.Println(err)
    }
    if err != nil {
        fmt.Println(err)
    }
    return v1, err
}

when i print the out1 i get something like this [48 46 49 50 48 49 49 55 10]. CAn you please help how to get the exact output in out1 and how to convert it into float64?

A: The conversion fails probably because there is some whitespace or newline character on s1. Try to trim it first before doing the conversion. Use strings.TrimSpace() to achieve that.
v1, err1 := strconv.ParseFloat(strings.TrimSpace(s1), 64)


text:
Q: ARIMA(0,2,2) model - equation derivation So on wikipedia here under Examples, it is mentioned that ARIMA(0,2,2) is given by:
$$
X_t = 2X_{t-1} - X_{t-2} + (\alpha + \beta -2)\epsilon_{t-1} + (1 - \alpha)\epsilon_{t-2} + \epsilon_t \ \ \ \ \ (1)
$$
My question is: how this equation has been derived?
We know that ARIMA(0,2,2) means $d=2$ (second order differencing) and $q=2$ is the MA (moving-average) order.
If $MA(q)$ is given by:
$$
X_t = \mu + \epsilon_t + \theta_1\epsilon_{t-1} + ... + \theta_q\epsilon_{t-q}
$$
therefore (?):
$$
X_t = \mu + \epsilon_t + \theta_1\epsilon_{t-1} + \theta_2\epsilon_{t-2} \\
X_{t-1} = \mu + \epsilon_{t-1} + \theta_1\epsilon_{t-2} + \theta_2\epsilon_{t-3}
\\
X_{t-2} = \mu + \epsilon_{t-2} + \theta_1\epsilon_{t-3} + \theta_2\epsilon_{t-4}
$$
After removing $\epsilon_{t-3}, \epsilon_{t-3}$, for the second order differencing we compute $X_t - 2X_{t-1} + X_{t-2}$:
$$
X_t - 2X_{t-1} + X_{t-2} = (\theta_1 - 2)\epsilon_{t-1} + (\theta_2 - 2\theta_1 + 1)\epsilon_{t-2} + \epsilon_t
$$
and the coefficients of the error terms differ from those in (1).

A: Ok I realised that we just need to substitute:
$$
\alpha = 2\theta_1 - \theta_2 \\
\beta = -\theta_1 + \theta_2
$$
although I do not quite understand what was the reasoning behind this particular substitution.


text:
Q: Alternative for "seats" in expressions such as "40% of the total seats are reserved for students of backward cast" All of the leading educational institutes have 60% of their seats reserved for students of backward castes. It is a fairly common expression and a sad fact in India.
What would be an alternative to the word "seat" in this sentence? Even though it is very popular here, I am sure it has been used incorrectly because I did not find any meaning for the word "seat" which could be used over here.

A: Higher Education institutions offer places in the UK. It may be the same in other regions.
I might prefer lower caste for backward cast but that wasn't part of the question.

A: I would suggest enrollments, or perhaps admissions.

A: You might say that they reserve 60% of their openings or positions to members of the lower classes.

A: Over here in Aus you might also hear intake being used to refer to the overall group/period/people entering university so you could say that 60% of the institution's target intake is reserved?
Sample usage : RMIT's mid-year intake or Monash's 2005 key dates (Fri 31, Dec 2004 is the last day of the Feb intake).

A: All of the leading educational institutes have 60% of their quotas reserved for students of backward castes.


text:
Q: Keep alive solution for cron job I have a hosted websolution and a script that update information backend for the site.
My webhost allows cron and I have made a script that wget's to every hour.
The script checks the db-table with posts to update for the oldest updated post and update that. In the end of the script I use javascript refresh to do the same procedure again this time with the second oldest updated post and so on until all posts are run through. If I open the script in my browser it works fine but when my host sets up the cron the script does not continue after the javascrpt refresh.
How can I solve this with another refresh solution that will work until the my statement stops it just by letting cron start the script?
(I changed to this solution from one where all posts were updated in one pageload but since it started to time out I went with this)
script.php
$limit=3600;

//Select the oldest updated post

if($last_update<$update_to_limit){ //check if the post was updated during this run

        // Script that update the post and below the java refresh that repeats the script.

    ?>
        <script type="text/javascript">
                <!--
                window.location.href = "http://www.site.se/script.php"
                //-->
        </script>
    <?php
    }else{
        echo 'OK : All posts updated within the last : '.$limit.' s';
    }

A: Wget will not run Javascript, if you open your code from the browser, it will of course run it, that is the reason of the difference.
I don't really suggest the method you're trying to use. If you really want, you can call wget again from PHP, use cURL or I guess even header('Location..');. But it would be much nicer to solve this problem in one turn.
If your code times out, I'd recheck the way that PHP code is written, and try to find a better solution, that is not so time-consuming. Afterwards: is the DB good enough, are the indexes set, etc. Or, if you cannot optimize it (or you do not want to), you can use set_time_limit().
(One more thing: Java!=Javascript. If you want to shorten it, write js instead of java)


text:
Q: duplicate key value violates unique constraint, but shouldn't I have two tables, one called 'persons' the other called 'results'.
persons has an ID, and a playername.
Results has an ID, a playerID, and a score and time.
It seems logical to me that the "playerID" in results should not be unique (since the same player can have multiple scores), though when executing this query:
insert into results (playerid, score, time) values
((select id from persons where playername = 'Dylan'),100,100);

I get the error
ERROR:  duplicate key value violates unique constraint "results_playerid_key"
DETAIL:  Key (playerid)=(1) already exists.

Is this perhaps an error on the database? (The database is managed by several lecturers at my university, and I have no way of changing any settings).
Thanks for any insight you can provide.

A: Although it may seem logical to you (and indeed to me) maybe it does not sound logical to the people managing the DB, so that they put a constraint on playerid as unique.
Maybe there was a mistake and they wanted to set the id as an autoincrementing primary key? Can you at least investigate the schema to see what constraints are on even if you cannot change them?
It may well be that the idea behind the DB is to really have one result per player, do you know the business or application logic potentially sitting behind this choice?

A: Have you tried renaming the foreign key in the results table to something that isn't "playerid" (I'd use player_id or player_no)?  Also make certain that it's a number in the results table, and not set to a unique value.


text:
Q: Firestore Geo Queries Is there any way to query firestore db and return results order by distance (ascending/descending) from user's current location.
https://firebase.google.com/docs/firestore/solutions/geoqueries
This above documetation GeoQuery return documents with in the range but not in sorted order even after giving a direction.
    public Query getDocuments(MainActivity mActivity, GeoQueryBounds bounds) {
    return FirebaseFirestore.getInstance()
                            .collection("user")
                            .whereEqualTo("type", Integer.valueOf("1"))
                            .orderBy("geoHash", Query.Direction.ASCENDING)
                            .startAt(bounds.startHash)
                            .endAt(bounds.endHash)
                            .limit(10);

A: The ways these libraries work means they by definition don't get the results from the database in order of distance. So if any library returns them in distance order, it's because they post-process the data.
If you use the approach in the documentation, you can post-process it in your application code. The code samples for querying geohashes has an example of using GeoFireUtils.getDistanceBetween() to determine the distance.


text:
Q: Trying to detect keypress I made a method that detects when a key is pressed, but its not working! Heres my code
void KeyDetect(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.W && firstload == true)
    {
        MessageBox.Show("Good, now move to that box over to your left");
        firstload = false;
    }
}

I also tried to make a keyeventhandler but, it sais "cannot assign to key detect because it is a method group"
public Gwindow()
{
    this.KeyDetect += new KeyEventHandler(KeyDetect);
    InitializeComponent();
}

A: Use keypress event like this:
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyCode == Keys.F1 && e.Alt)
    {
        //do something
    }
}

A: 1) Go to your form's Properties
2) Look for the "Misc" section and make sure "KeyPreview" is set to "True"
3) Go to your form's Events
4) Look for the "Key" section and double click "KeyDown" to generate a function to handle key down events
Here is some example code:
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        Console.WriteLine("You pressed " + e.KeyCode);
        if (e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0)
        {
            //Do Something if the 0 key is pressed (includes Num Pad 0)
        }
    }

A: You are looking for this.KeyPress. See How to Handle Keypress Events on MSDN.

A: Try to use the KeyDown event.
Just see KeyDown in MSDN

A: Just do
if (Input.GetKeyDown("/* KEYCODE HERE */"))
{
    /* CODE HERE */
}


text:
Q: How to write a complete web application? These questions were asked me in a technical interview:

*

*If we deploy an application on multiple server (like database server, web server) then, each request should be redirected to proper server, then how you will handle it in your code?

*How security pinholes will be handled in an application?

*What things should be considered while writing a web application?

*How will you do load/performance testing of web application? Which framework you will use for it?

*How will you implement a cache for results which require a DB access?

Please let me know how to write an web application considering all these points. I am not so much aware of architechural design of web application.
Your guidelines will be helpful.

A: Rather than give you an answer to an interview question, I'll point you in the right direction.  This is important stuff to know, so to be better prepared for your next interview, you'll want to study.  The problem sounds like you don't even know where to start.
Distributing your web app across multiple servers is done for Load Balancing.  It's not entirely a development issue, but as a developer you do need to be aware of some things.
I'd start here and then google "load balancing asp.net" for further reading.

A: At this point, I can only answer your question like this:

*

*look at how others do it

*look at popular frameworks for the platforms you're willing to use, try understanding what they do, why they do it, and how they accomplish it

*read a lot

*try hard yourself

*learn from the numerous mistakes you will make

You cannot get experience from our answers, nor from books. Only by doing things.
For starters, you may rather want to set up a website using a popular open source CMS of your choice, work with it, and learn about configuration etc. Then start writing pluggins and then - like any developer - become convinced that you can do it MUCH better than anyone else. And once you're done with that phase, you're good to go ;)
greetz
back2dos


text:
Q: Protractor Max Call Stack Error I've been using Protractor for quite awhile now and am familiar with a range of errors related to Protractor, Webdriver, Jasmine etc.  Recently, I've encountered one I haven't seen before:
A Jasmine spec timed out. Resetting the WebDriver Control Flow.

/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:714
    super(opt_msg);
         ^
RangeError: Maximum call stack size exceeded

While I have seen maximum call stack errors before, they are typically related to recursive functions or ridiculously large for loops.
So I am a little lost on what this means for Protractor/Webdriver.  Per my understanding, this is a browser-related error. But I don't have much JavaScript going directly to the browser (just some forced clicks, and logging a few objects).
Also, I have only seen this error while running my entire suite of tests (~500 specs), but it does not happen every time and it also does not occur in the same spot which concerns me... it's a flaky error.
Does anyone have an explanation for this error?

A: One of the reasons Maximum call stack size exceeded error occurs is when a function calls itself. For example
let next = async function () {
    await $nextButton.click();
    await next(); // function calls itself here
}

What happens here is the code gets in an infinite loop and throws the error
Thus just go over your code and make sure you don't do it somewhere by accident


text:
Q: My Random array is giving me the same answer when it should be different I got my code to work in the expected way, but when i try to make more than one list of permutations it gives me the first one and doesn't change it around.
I need to make a list of permutations from 1 to 10 using an Arraylist and to catch one error that can occur in the code. Then we have to duplicate that code so that we get 9 DIFFERENT lines of permutations.
 import java.util.ArrayList;
import java.util.Random;
public class Permutations
{

    ArrayList <Integer> Perm = new ArrayList <Integer> ();
    ArrayList <Integer> Print = new ArrayList <Integer> ();
    int counter = 9;
    int List = 1;
    public void ArrayList()
    {
        Perm.add(1);
        Perm.add(2);
        Perm.add(3);
        Perm.add(4);
        Perm.add(5);
        Perm.add(6);
        Perm.add(7);
        Perm.add(8);
        Perm.add(9);
        Perm.add(10);
    }

    public void PermutationGenerator()
    {
        ArrayList();
        Random rand = new Random();
        int value = rand.nextInt(10) + 1;
        while(Print.size() < 10)
        {
            try
            {
                while(Print.contains(value))
                {
                    value = rand.nextInt(10) + 1;
                }
                Print.add(value);
                Perm.remove(value);
            }
            catch(IndexOutOfBoundsException a)
            {
                System.out.println("");
            }
        }
        System.out.println("List" + List + ":" + Print.toString());
        List++;
        if(List < 10)
        {
            PermutationGenerator();
        }
    }

This is what is printed out:
List1:[9,6,5,4,10,2,8,7,1,3]
List2:[9,6,5,4,10,2,8,7,1,3]
List3:[9,6,5,4,10,2,8,7,1,3]
List4:[9,6,5,4,10,2,8,7,1,3]
List5:[9,6,5,4,10,2,8,7,1,3]
List6:[9,6,5,4,10,2,8,7,1,3]
List7:[9,6,5,4,10,2,8,7,1,3]
List8:[9,6,5,4,10,2,8,7,1,3]
List9:[9,6,5,4,10,2,8,7,1,3]

A: At the end of the PermutationGenerator, you calle the same method recursively. In that point, the variable Print have already 10 random elements inside.
Each time the PermutationGenerator method is executed, you need to empty the Print variable, so the while loop is executed. In your case, the Print variable have always the same 10 elements, so the while loop is executed only the first time, and the Print variable is never modified.

A: import java.util.ArrayList;
import java.util.Random;

public class Permutations {

    ArrayList<Integer> Perm = new ArrayList<Integer>();
    ArrayList<Integer> Print = new ArrayList<Integer>();
    int counter = 9;
    int List = 1;

    public void ArrayList() {
        Perm.add(1);
        Perm.add(2);
        Perm.add(3);
        Perm.add(4);
        Perm.add(5);
        Perm.add(6);
        Perm.add(7);
        Perm.add(8);
        Perm.add(9);
        Perm.add(10);
    }

    public void PermutationGenerator() {
        ArrayList();
        Random rand = new Random();
        int value = rand.nextInt(10) + 1;
        //list: 1-9
        while (Print.size() < 10) {
            try {
                while (Print.contains(value)) {
                    value = rand.nextInt(10) + 1;
                }
                Print.add(value);
                Perm.remove(value);
            } catch (IndexOutOfBoundsException a) {
                System.out.println("");
            }
        }
        System.out.println("List" + List + ":" + Print.toString());
        List++;
        if (List < 10) {
            Print.removeAll(Print);
            PermutationGenerator();
        }
    }
    public static void main(String[] args) {
        Permutations permutations = new Permutations();
        permutations.PermutationGenerator();
    }
}

A: I got the answer to show up if i add this line to the final while loop.
if(List < 10)
    {
        Print.removeAll(Print);
        PermutationGenerator();
    }


text:
Q: SQL join for filling missing values I have a table of historical data (#Records); at the end of a sproc I need to fill the data against a table of dates (dbo.MasterDates). For the following simplified example, I'll simply use City as the identifier for a unique series of data.
tempdb.dbo.#Records:

Date
City
Value

2021-06-04
LA
10.5

2021-06-04
NYC
11.2

2021-06-05
LA
9.2

2021-06-06
NYC
8.1

dbo.Dates:

Date
Year
Month
Day

2021-06-04
2021
6
4

2021-06-05
2021
6
5

2021-06-06
2021
6
6

If the data was filtered so there was only one series being retrieved (i.e., only data for NYC), filling would be a simple select from dbo.Dates and a left outer join on #Records. However, I need to fill such that there is a record for each day, for each unique City.
e.g. (filled records bolded)

Date
City
Value

2021-06-04
LA
10.5

2021-06-04
NYC
11.2

2021-06-05
LA
9.2

2021-06-05
NYC
0.0

2021-06-06
LA
0.0

2021-06-06
NYC
8.1

My first attempt was to create a version of the dbo.Dates with records for each unique city, and then use this to fill the #Records table:
insert into #FilledDates (Date, City)
select
    dates.Date, City
from Dates d
cross apply
(
    select distinct City from #Records
) r

select
    d.Date, d.City, isnull(r.Value, 0)
from #FilledDates d
left outer join #Records r on r.Date = d.Date and r.City = d.City

This works fine; however, given that the actual use case is much more complex, I'm curious if there is a better way to achieve the desired result. The performance is my main concern... It seems like I should be able to combine the cross apply & join steps, however I'm still a bit new to cross apply.

A: Create a projection with all the possible city/date combinations, and then join to that:
WITH Projection AS (
    SELECT City, [Date]
    FROM Dates
    CROSS JOIN (SELECT DISTINCT City FROM Records) c
)
SELECT p.*, coalesce(r.[Value], 0.0) as [Value]
FROM Projection p
LEFT JOIN #Records r ON r.[Date] = p.[Date] AND r.City = p.City
ORDER BY [Date], City

See it work here:

http://sqlfiddle.com/#!18/bebc4/4/0


text:
Q: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)) I am new in ubuntu and i am trying to download ROS at the moment. the idea of repository keyrings are still new. However i am getting somewhere and making progress.
this error seems to render my installation useless, please help me out of this.
I have tried the ls/etc/apt/sources.list.d and rm files..
but nothing happened.
the next message tells me to 'Manage keyring files in trusted.gpg.d instead'
what to do please guide.
thanks


text:
Q: TCL - List with Variables I am having trouble creating a list of lists that contains a mixture of text and variables in TCL. I have a user input variable that I then want to plug into a list. I will skip the user select option for brevity.
set a 0.1
set b 20.0

set c {
    {text1 text2 $a text3}
    {text4 text5 $b text6}
}

foreach i $c {
    set CheckVal [lindex $i 2]
    puts "Threshold is $CheckVal"
}

Resultant output:
Threshold is $a
Threshold is $b
Desired output:
Threshold is 0.1
Threshold is 20.0

A: While the methods suggested by Peter Lewerin work, they should only be used as a last resort. Normally you would use some of the commands that operate on lists to create your list of lists. I believe that is what glenn jackman was alluding to.
Depending on your actual code, I would probably use list and/or lappend:
set c {}
lappend c \
  [list text1 text2 $a text3] \
  [list text4 text5 $b text6]

Then the foreach will work as you wrote it.

A: Two alternatives are
set a 0.1
set b 20.0

set c {
    {text1 text2 a text3}
    {text4 text5 b text6}
}

foreach i $c {
    set CheckVal [lindex $i 2]
    puts "Threshold is [set $CheckVal]"
}

Store the variable name instead of the value, and get the value by a two-step substitution ($$Checkval doesn't work, but [set $CheckVal] does) in the puts invocation.
set a 0.1
set b 20.0

set c {
    {text1 text2 $a text3}
    {text4 text5 $b text6}
}

foreach i $c {
    set CheckVal [lindex $i 2]
    puts [subst "Threshold is $CheckVal"]
}

This is double substitution rather than two-step substitution. It looks simple, but subst is actually a bit tricky and is almost a last-resort technique.
Regardless of which solution you use, this kind of scheme where you store a reference to a variable value in a structure is fragile since it depends on the original variable being in scope and still existing when the reference is dereferenced. At the very least, you should store a qualified name (namespace and name) in your list. If the variable is a local variable, you need to use it during the same call as when it was stored (or from further up the call stack using upvar, but don't go there).


text:
Q: I want to aggregate data each same date I want to aggregate data each same date.
I wrote SQL in BigQuery.
Now there is a table like
id | date                  | country | code
1    2015-10-16T12:00:30     Japan     A
2    2015-10-16T12:00:30     America   C
3    2017-08-20T15:50:44     America   B
4    2016-22-56T11:32:01     China     E
5    2017-08-20T15:50:44     EU        D

I want to change upper tabble into this

id    | date                  | country       | code
1,2    2015-10-16T12:00:30     Japan,America    A,C
3,5    2017-08-20T15:50:44     America,EU       B,D
4      2016-22-56T11:32:01     China            E

It is like  put together id・country・code in each date.
How should I write query to do this?

A: You can use bigquery string_agg function in standard sql.
select string_agg(id, ',') as id
    , string_agg(country, ',') as country
    , string_agg(code, ',') as code
from tableA
group by date

Note: You need to enable first standard sql support. Using this
  link

Legacy SQL, you can use group_concat() function. See this link.
 select group_concat(id, ',') as id
        , group_concat(country, ',') as country
        , group_concat(code, ',') as code
 from tableA
 group by date


text:
Q: Flutter read shared preferences in main then decide which startup page? I want to judge which page to start up in main (actually is login page and the home page). So I have to read isLogin in preferences. How to do that in main?
I tied these codes:
Future<Null> checkIsLogin() async {
  String _token = "";
  // If token exist already, then HomePage
  SharedPreferences prefs = await SharedPreferences.getInstance();
  _token = prefs.getString("token");
  print('get token from prefs: ' +  _token);
  if (_token != "" && _token != null) {
    // already login
    print("alreay login.");
    isLogin = true;
  }
}

void main() {
  App.init();
  // if we have token then go to HomePage directly otherwise go to LoginPage.
  Widget _defaultHome = new LoginPage();
  checkIsLogin();
  if (isLogin) {
    _defaultHome = new HomePage();
  }

  runApp(new MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: globalThemeData,
      home: _defaultHome
  ));
}

above code, isLogin is an global variable. There was an error:
Performing full restart...
Restarted app in 2,810ms.
[VERBOSE-2:dart_error.cc(16)] Unhandled exception:
Invalid argument(s)
#0      _StringBase.+ (dart:core/runtime/libstring_patch.dart:245:57)
#1      checkIsLogin (file:///Volumes/xs/awesome/uranus/clients/flutter/flutter_asgard/lib/main.dart:17:34)
<asynchronous suspension>
#2      main (file:///Volumes/xs/awesome/uranus/clients/flutter/flutter_asgard/lib/main.dart:29:3)
#3      _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
#4      _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

Seems there are issue to call async in main, how to get it to work?

A: You need await checkIsLogin.
This is my code:
Future<Null> main() async {
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeRight,
    DeviceOrientation.landscapeLeft,
  ]);
  Screen.keepOn(true);
  SharedService.sharedPreferences = await SharedPreferences.getInstance();
  account = SharedService.sharedPreferences.getString("Account");
  password = SharedService.sharedPreferences.getString("Password");
  runApp(new MyApp());
}

A: Load the Homepage and if the user is not logged in, then replace it with your LoginPage()
@override
  void initState() {
    super.initState();
    checkIsLogin();
 }

Future<Null> checkIsLogin() async {
    String _token = "";
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _token = prefs.getString("token");
    if (_token != "" && _token != null) {
      print("alreay login.");
      //your home page is loaded
    }
    else
    {
      //replace it with the login page
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => new LoginPage()),
      );
    }
  }

A: Create a SplashPage that you can pass as a home route in your MaterialApp()
Inside SplashPage, for example initState() you can check for login and than push new route to a Navigator.
SplashPage can just be centered logo, with optional animation.

A: This is what i did,
void main() {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences.getInstance().then((instance) {
    StorageService().sharedPreferencesInstance = instance; // Storage service is a service to manage all shared preferences stuff. I keep the instance there and access it whenever i wanted.
    runApp(MyApp());
  });
}

Then in the Material App Build
@override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App Title',
      home: _checkUserLoggedIn()
          ? HomeScreen()
          : LoginPage(),
    );
  }

_checkUserLoggedIn Function
bool _checkUserLoggedIn() {
    return _storageService.getFromShared('isLoggedIn'); //  Just a get method from shared preferences
}

A: Here is what you can do
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() async {

  String initialRoute;

  // handle exceptions caused by making main async
  WidgetsFlutterBinding.ensureInitialized();

  // init a shared preferences variable
  SharedPreferences prefs = await SharedPreferences.getInstance();

  // read token
  String token = prefs.getString('token');

  // use dart's null safety operater
  if (token?.isEmpty ?? true)
    initialRoute = 'login';
  else
    initialRoute = '/';

  // create a flutter material app as usual
  Widget app = MaterialApp(
    ...
    initialRoute: initialRoute,
  );

  // mount and run the flutter app
  runApp(app);
}

For more details, you can refer to this article: https://www.ravsam.in/blog/dynamic-home-route-in-flutter-app/


text:
Q: how to create Html form to send email with button Unable to get ths form working.
Is there any easy to create html form that will simply send email upon submission?
Can anyone provide some code samples?
I tried to get it workin but it always stay there no response on email. In form i tried to get date, time, locations that can be typed, number passanger and cars, car type, name email and message.
                <form class="booking-form">

                                <fieldset class="car-type">
                                    <input type="checkbox" name="car-tclass="icon-car-LUXURY SEDANype" id="LUXURY SEDAN" />
                                     LUXURY SEDAN
                                </fieldset>

                                <fieldset class="car-type">
                                    <input type="checkbox" name="car-type" id="EUROPEAN SEDAN" />
                                    EUROPEAN SEDAN
                                </fieldset>

                                <fieldset>
                                    <input type="text" name="name" placeholder="Name" />
                                </fieldset>
                                <fieldset>
                                    <input type="email" name="email" placeholder="Email" />
                                </fieldset>

                                <fieldset>
                                    <input type="text" name="from1" placeholder="From" />
                                </fieldset>
                                <fieldset>
                                    <input type="text" name="to1" placeholder="To" />
                                </fieldset>

                                <fieldset>
                                    <input type="text" name="date" placeholder="Date1" class="datepicker" />
                                </fieldset>
                                <fieldset>
                                    <input type="text" name="time" placeholder="Time" class="timepicker" />
                                </fieldset>

                                <fieldset>
                                    <select name="cars">
                                        <option>Cars</option>
                                        <option>1</option>
                                        <option>2</option>
                                        <option>3</option>
                                        <option>4</option>
                                    </select>
                                </fieldset>
                                <fieldset>
                                    <select name="passengers">
                                        <option>Passengers</option>
                                        <option>1</option>
                                        <option>2</option>
                                        <option>3</option>
                                        <option>4</option>

                                    </select>
                                </fieldset>

                                <fieldset>
                                    <textarea name="message2" placeholder="Message"></textarea>
                                </fieldset>

                                <button class="btn btn-primary">Book Now</button>

                    </form>

A: you need a backend language

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
    <input type="text" name="someText" placeholder="someText">
    <input type="submit" name="sendText" value="sendText">
</form>

and with php you can send the data form form
<?php

    $errorMessage = ''; // case the user not complete all fields of the form
    $to = 'myemail@company.com'; // destiny of message

    if( isset($_POST['sendText']) ){ // comprobate the action of the input type submit
        $someText = $_POST['someText']; // get the value of input type text
        if( !empty($someText) ){ // comprobate if the variable is not empty
            $someText = stripslashes(trim(filter_var($someText , FILTER_SANITIZE_STRING))); // this sanitize the text for avoid the code injection
            mail($to,$someText); // this method only can send message when the web is working on server
        }else{ // show an error message if text is empty
            $errorMessage.="Please complete all fields
";
        }
    }

?>


text:
Q: does every correct mathematical proof have to be sound argument? We know that if an argument is sound then it must be valid and its all premises must be true (as a result of this its conclusion is also true).
We prove mathematical statement by using logic rules. Then, can we say that all correct mathematical proofs are sound arguments?
I think that the answer is yes because a proof must be valid to reach the conclusion and if it is a correct proof that its premises and conclusion must also be true, but i am not sure about it? What is your notions?

A: 'True' is the sticky notion here. In real life, when we say that a statement is true, we mean true in our world. Thus, for example, any argument that starts out with: "Grass is purple ..." will not be a sound argument.
However, when mathematicians talk about 'truth' they mean that it describes some abstract mathematical world, e.g. the world of numbers, or the world of sets. And these kinds of mathematical worlds can really be anything the mathematician wants it to be. So in that context, a sound argument would be one whose premises are basically the axioms that the mathematician used to define that world.
For example: in the mathematical world of Euclidian geometry, a sound argument could start with "the angles in a triangle add up to the sum of two right angles", but any such argument is automatically not sound in the mathematical world of non-Euclidian geometry.


text:
Q: Jenkins Agent Security I have 2 questions that Im trying to figure out.
QUESTION 1
I have setup a Jenkins Master and am trying to create a Agent using the UI. Here is the UI snippet.

Now when I click Save and open the Agent, it tells me to use this command to conenct.
java -jar agent.jar -jnlpUrl https://<MASTER_NODE>/computer/Test_node/slave-agent.jnlp

It is not giving me the option to use -secret. How can I enable that feature so that I also need to provide the secret to connect to my master.
QUESTION 2
I am in the process of automating the creation of multiple Jenkins Agents. Im going to do that using REST API calls. The command is
curl -s -k -w %{http_code} -X POST "https://<MASTER_NODE>/computer/doCreateItem?name=jenkins-slave-1&type=hudson.slaves.DumbSlave" \
                        -H "Content-Type: application/x-www-form-urlencoded" \
                        -H "Jenkins-Crumb: ${JENKINS_CRUMB}" \
                        -d "json=${JNLP_JSON}" )

Now the thing is for every agent, the secret value inside the jnlp file is different. Is there a way to specify that value in the Jenkins Master so that every Jenkins Agent has the same password ?

A: If you are the jenkins admin, check
1) Manage Jenkins -->Configure Global Security-->Access Control-->Authorization
under Project-based Matrix Authorization Strategy, make sure you have not ticked the Connect options under Agent for Anonymous role.
(or)
2) Make sure Manage Jenkins--> Configure Global Security-->Agents-->Agent protocols has only V4 enabled
JNLP V4 TLS based encryption
As for your second question I do not know. am facing the same issue of how to connect the slaves automatically to the Jenkins Master with different Secrets

A: JNLP Secrets are derived from the Agent's name. You could get the JnlpMac or secret for a specific agent from the jnlp file or via groovy executed on the master. See for example How to find JNLP Node's secret key remotely?

A: You can add jenkins-slave.exe and jenkins-slave.xml in Remote root directory which contains jre argument this need a secret key. Secret key only needed when you are setting agent as windows service.
I have followed instruction in LINK


text:
Q: Hilbert Space as Direct Sum of Subspaces Let $H$ be a Hilbert space, such that $H = W_1 \bigoplus W_2$, i.e., $H$ is direct sum of two subspaces $W_1$ and $W_2$.
Is it true that $W_1,W_2$ are closed ? If I assume the Axiom of Choice, I can show the existence of a counter example. But can someone give a solid counter example ?


text:
Q: Render code into MVC view using jQuery I have a string  that reaches my controller in the form of a string. It is a List(Model.ToParticipantList) that has the following element template :
string.Format("

{1}

,", el.Id, el.Name, "To"));

I would like this to pass to my jQuery function and result the following:

System System

This works:
             document.getElementById('To1').innerHTML=@Html.Raw(Model.ToParticipantList);  //this works
          // $("#To1").html('@Html.Raw(Model.ToParticipantList)');  //this doesn't
          // $("#To1").append('@Html.Raw(Model.ToParticipantList)'); //this doesn't

What am I doing wrong in the last 2 examples ?

A: Any of the approaches for inserting the HTML should work. If you take this simple example:

It will render this HTML in the DOM:

Using getElementById

Using jQuery html

Using jQuery append

Essentially they all achieve the same results. There must be something going on in the code that you are not showing in your example. I did notice in your code listing that the when you use getElementById the Html.Raw is not surrounded by single quotes like you are doing for the jQuery html and append methods. If you are including the single quotes in the string contained in ToParticipantList it will not work.


text:
Q: Not able to connect to Hadoop Server using HadoopFileSystem in pyarrrow I am trying a python code in which I am using pyarrow and trying to make connection to hadoop server using fs.HadoopFileSystem(host=host_value, port=port_value) but everytime I am getting an error message:
    self.parquet_writer = HDFSWriter(host_value='hdfs://10.110.8.239',port_value=9000)
    File "/app/aerial_server.py", line 54, in __init__
        self.hdfs_client = fs.HadoopFileSystem(host=host_value, port=port_value)
    File "pyarrow/_hdfs.pyx", line 89, in pyarrow._hdfs.HadoopFileSystem.__init__
    File "pyarrow/error.pxi", line 143, in pyarrow.lib.pyarrow_internal_check_status
    File "pyarrow/error.pxi", line 114, in pyarrow.lib.check_status
    OSError: HDFS connection failed

env variables
    PYTHON_VERSION=3.7.13
    HADOOP_OPTS=-Djava.library.path=/app/hadoop-3.3.2/lib/nativ
    JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
    HADOOP_INSTALL=/app/hadoop-3.3.2
    ARROW_LIBHDFS_DIR=/app/hadoop-3.3.2/lib/nativeHADOOP_MAPRED_HOME=/app/hadoop-3.3.2
    HADOOP_COMMON_HOME=/app/hadoop-3.3.2
    HADOOP_HOME=/app/hadoop-3.3.2
    HADOOP_HDFS_HOME=/app/hadoop-3.3.2PYTHON_PIP_VERSION=22.0.4
    CLASSPATH=/app/hadoop-3.3.2/bin/hdfs classpath --glob
    HADOOP_COMMON_LIB_NATIVE_DIR=/app/hadoop-3.3.2/lib/native
    PATH=/usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/app/hadoop-3.3.2/sbin:/app/hadoop-3.3.2/bin
    _=/usr/bin/env


text:
Q: laravel breeze app.css, app.js missing when inspected I'm new to Laravel Breeze and tailwind.
After successfully installed Laravel Breeze and looking at /login page source, I couldn't match the source code and actual page source and would like to know what's going on.
In app.blade.php or guest.blade.app there are the following lines.
    <!-- Styles -->
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">

    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}" defer></script>

But when viewing login page source, it has
    <!-- Styles -->
    <style>
        /*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}a{background-color:transparent} ...
     </style>

    <style>
        body {
            font-family: 'Nunito';
        }
    </style>

And no javascript is loaded.
I'm expecting to see just the link to public/css/app.css and public/js/app.js but no such thing here.
So if anyone can explain how Laravel Breeze works regarding to including css and js
and how I can extend tailwind css to other pages and use js in other pages, I'd really appreciate.

A: You need to compile the assets installed with Breeze. To do so, just run the following commands on your project directory:
npm install
npm run dev

If you check the Public folder on your Laravel app, you should see the CSS and JS compiled. Refresh the page, and the style should look OK.
Documentation reference:
https://laravel.com/docs/8.x/starter-kits#laravel-breeze-installation


text:
Q: How to change app theme from ordinary "Blank Activity" to "Master/Detail Flow" I have an application that works on the basic theme "Blank Activity" and what i would like to do is to change it to a "Master/Detail Flow" theme. I do know that this will make my application work on android SDK 11 + (android 3.0 Honeycomb +), that is OK with me. The issue is i don't know where to start from, what are the basic steps to make this BIG conversion? I couldn't find any example to help me out with this issue. What should i be looking for. i am sure this has been done, can you at least please give me some pointer on how to do this?
my Application is not that complicated it uses activities, async tasks, DB, custom lists,... it is very basic. I use the custom list to display data and when i click on it it displays much more details, so I thought what better way to do this in a more professorial matter than the "Master/Detail Flow". If you have any tutorial regarding the "Master/Detail Flow" that you can hook me up with that might help.

A:
I have an application that works on the basic theme "Blank Activity"
  and what i would like to do is to change it to a Master/Detail Flow"
  theme.

I think a change of the application flow would be more appropriate then a change of theme. Two obvious questions that would appear are why do you suddenly want to make this change and are sure your app makes sense in a master/detail flow? The answer would most likely be positive but you should answer them nonetheless.

I do know that this will make my application work on android SDK 11 +
  (android 3.0 Honeycomb +), that is OK with me

I don't see why you're app couldn't run on versions below with the new master/detail stuff.

The issue is i don't know where to start from, what are the basic
  steps to make this BIG conversion? I couldn't find any example to help
  me out with this issue. What should i be looking for. i am sure this
  has been done, can you at least please give me some pointer on how to
  do this?

You haven't provided details about how is your app implemented. The change would revolve around fragments so a BIG question would be if the current single pane version is built using the fragments framework.
If your app is built using fragments then making the change shouldn't be too hard. You'd need to:

*

*establish which parts(fragments) should be combined in an activity(from your old ones) to make the master/detail(when the space would allow it)

*change the multi pane activity to accommodate the new fragment(s). This should be easy to do but it would depend on the size of the features exposed by each of those fragments.

*modify the rest of the activities(for when the app will not run in the multi pane mode), this would be small changes as the activities would mainly remain as the current version

If your app isn't built using fragments, then what I said above still applies but you'd need to also actually make the required fragments wrapping whatever functionality your app has. This would most likely result in a big code refactoring.

A: Here is a tutorial about the Master/Detail template in Android - An Android Master/Detail Flow Tutorial.
As far as I understand your application is up and running - so I'm not sure whether it is worth it to try rewriting it, unless you are experiencing some problems of course. :)
In general the master/details flow requires the following steps:

*

*Implement a ListFragment showing basic information of your items

*Implement a Fragment showing detailed information about a particular item

*Make an xml layout file for large devices (located in layout-sw600dp folder for example). In this layout you have to put both your fragments.

*Write a general version of this layout file (i.e. file with the same name but located in the layout folder), which contains only the ListFragment.

*Let your activity handle onItemClick event from the ListFragment. Each time an item is clicked, you have to check if the activity is showing both fragments or only the ListFragment. If both are visible, you have to notify the details fragment that new item is selected so it can show its data. Otherwise you have to create new details fragment (you reuse it of course), pass it some information about the selected item (so it can show the item's data) and replace the ListFragment with the new one.

That a basic overview, but it should be enough to give you some idea about this flow. If you need any more details - just let me know. :)

A: Here are some links from developer.android.com fragment-ui and adaptui
These are some guidelines about fragments but they are told using a master/Detail app.
Also dont forget to checkout the news reader app provided as sample in the second link.

A: Master/detail flow and blank activity is not same as you want to change by only changing app theme or app base theme. It will be better, if you first design master/detail flow template using UI fragments, then according integrate you blank activity with the master template making necessary changes. And for master/detail flow tutorial just google it, you will find lots of example there.

A: If you have a recent version of the Android SDK, you should be able to create a new Android application and during that process you can elect to have the wizard create a Master/Detail Flow app for you. It will create a basic working app so that you can look through the code and understand the necessary parts.
Then, depending on how simple your app is, you may want to move all your present code to the new application or vise versa.
Macro changes that will happen:

*

*Change all your current Activities to extend Fragment instead.

*You will have to create a FragmentActivity to call your Fragments. This will basically be the boilerplate code, with just the names of your Fragments added to it.

*Don't forget to double check your Manifest!

In your converted Fragments that previously extended Activity:

*

*Everywhere you needed a Context, switch that with getActivty() (or create a global variable so that it is only called once)

*Change onCreate() to
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mView = inflater.inflate(R.layout.fragment_signals, container, false);
    setHasOptionsMenu(true); // Add if you want to display a Menu
     // Your initiation code here
    return mView;
}

*If you have a menu, change it to
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.activity_main, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

And that's it for basic applications. When you first change Activities to Fragments, there will be many errors. But, they are all easy to fix.


text:
Q: Dual Drive Dual Boot I have a new system with Ubuntu installed on the SSD with GPT and EUFI boot and LVM.  Now I want to install Windows 10 on a second SSD.  I want to be able to choose which OS to run and would like it to be as easy as possable.  What I want to know is the best way to install Win 10 on the second drive.  I was thinking that simply unplugging the Ubuntu drive and installing Win 10 and reconnecting the Ubuntu drive and using the bios to choose which OS to boot would work, but I would like a menu to come up when I reboot instead of waiting for the right moment to hit the select drive key.
I do not know about the LVM on Ubuntu and how it will work with Windows and more drives. I want to add a M2 drive later, for Win 10 and I plan to add HDs later for media storage only, but I dont know if there may be conflicts using LVM.  I want the media drives to be available to both OS.

A: From my experiences dual-booting Windows and Linux on two different SATA HDDS, the Windows bootloader will always overwrite the GRUB bootloader and will never show the Linux OS. So, I install Windows first, then Linux. When the Linux installer asks for the location to install the GRUB bootloader, I point it to the Windows EFI partition. Then GRUB will find the Windows install and add it to the boot menu. This works for my particular standard configuration in which I am dual booting Windows 10 64-bit and Ubuntu 20.04. I am NOT using LVM so I can't guarantee that this method will work for you.
delta1071

A: I would do as you suggested:

*

*Remove Ubuntu drive to install Windows

*Put the Ubuntu drive back in, and tell the UEFI to start Ubuntu rather than Windows.

*Reinstall GRUB so that it can find the Windows partition, and let you choose at boot time which you want.

I'd need to look a little further into it to find out exactly which GRUB commands to use, but this is how I would approach it.


text:
Q: extend to the end of Monday vs to the end of the day Monday vs to Monday I'd like to ask my teacher if she can extend the due date for an assignment, which I was supposed to hand in by the beginning(?) of Monday, to Monday 11:59 pm.
Which one is correct?
Is there a better way to say this?

Could you extend the due date to the end of Monday?
  Could you extend the due date to the end of the day Monday?
  Could you extend the due date to Monday?

A: In your example, the due date is already Monday, so you are asking for an extension of time on the due date.

extend the due date to Monday

is incorrect in your example, since the due date is already Monday.

end of the day Monday

may mean the end of business-day Monday, which is not what you want.

end of Monday

is closer to what you mean. However, to avoid ambiguity, teachers will usually specify

due by midnight on Monday

So you would be asking for an extension until 1 minute before midnight, which is essentially midnight.  In the current age of electronic assignment submissions, it can be easily enforced.
If your teacher only specified "Monday", you would have a valid argument that midnight is still a valid time to submit your assignment.

A: It's not idiomatically correct to say "extend the due date": it's a date which, like a number, is inherently not extensible.
You can change or delay or defer the due date, but taken literally that would only mean changing to a different day.
You can deal with both of these issues by using deadline rather than due date.

Could you extend the deadline until midnight?


text:
Q: Trying to make a slideshow with jQuery but can't get it to work Hi i am trying to make a slideshow for my webpage but i can't make it work. It is my first time using jQuery and im not so good at js either. Can someone see what i have done wrong?
Here are my html, css and js codes.
HTML

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" type="text/css" href="matsidacss.css">

    <title>Erik'p kokbok</title>

CSS
    .slider
{
    position:absolute;
    height: 205px;
    width: 230px;
    left: 50%;
    top:10px;
    margin-left:510px;
    overflow:hidden;
}

.slider img
{
    width:230px;
    height:205px;
}

Javascript
$(document).ready(function()
{
    $('#1').show("fade",2000);
    $('#2').delay(500).hide("slide", {direction:"left"}, 500);
    var sc=$(".slider img").size();
    var count=2;

    setInterval(function(){
    $("#1"+count).show("slide", {direction:"right"}, 500);
    $("#2"+count).delay(500).hide("slide", {direction:"left"}, 500);
    if(count == sc){
        count=1;
    }else{
        count=count+1;
    }
    }, 6500);
})

Thanks for helping//Anton

A: I explain you, I would change all the images' css but the first with display:none because '.hide' and '.show' changes the display, so you can't show something that is already showed.
So I will give you an example here JFiddle of how a Slider could work:
HTML

CSS
img {
    position: absolute;
    display: none;
}
#image1 {
    display: inline;
}

Javascript
var cont = 1;

setInterval(function () { //Make an action repeat each 1000 ms
    $("#image" + cont).hide("slide", {direction: "right"}, 500); //Go out
    if (cont == 3) { //To repeat the complete cycle
        cont = 1;
    } else {
        cont++;
    }
    $("#image" + cont).show("slide", {direction: "left"}, 500);  //Go in
}, 1000); //The 1000 ms

It is very commented and I think that it should be useful for you.
There is another way to do it, selecting all image elements or all the elements with the class "imageSlider", but it is way more complicated to understand compared with the way that I have showed you.
I hope it will useful to you.
Patch
PS: try to don't name your id with just a numbers.
PS2: the images aren't mine, I took it from google images.

A: Anton,
Not sure what your requirements are for the slideshow, but maybe you could use Twitter Bootstrap's slideshow.
http://twitter.github.io/bootstrap/javascript.html#carousel
It's effortless to get it up. Hope this helps.
Josh

A: Ive put together a jsfiddle for you : http://jsfiddle.net/XexmW/
There are a few issues with your markup/css/js.

*

*img tags dont need to have a close tag - im not sure it will be understood by all browsers. Use  instead.

*you still have an onload function call in your html

*"#1"+count wont sum 1 and count, then append it to #. if count = 1 then it would give you '#11'

*when i was playing around, i could only get the images to butt up against each other nicely if they have position:absolute

Here are my alterations:
html

css
    .slider
{
    overflow:hidden;
}

.slider img
{
    position:absolute;
    width:230px;
    height:205px;
    display:none;
    left:0;
    top:0;
}

Javascript
$(document).ready(function()
{
    $('#1').show();

    var sc=$(".slider img").size();

    var count=1;
    var lastCount = 0;

    setInterval(function(){

        lastCount = count;

        if(count == sc){
            count=1;
        }else{
            count++;
        }

        $("#"+count).show("slide", {direction:"right"}, 500);
        $("#"+lastCount).hide("slide", {direction:"left"}, 500);

    }, 1000);
})

Having said all that - if you can use an existing library or jQuery plugin, its likely to be more stable and x-browser compatible.


text:
Q: How to send true or false if there's data in child table in SQL Server? I have 2 tables that are related (parent-child), if there's any attachment added there will be an entry in the child table. We are fetching data using a stored procedure. I want to return true or false for every record. I have tried the following,
CREATE PROCEDURE [dbo].[testname]
(
    @Date DATE
)
AS

BEGIN

    SELECT TOP 10000
        s.column1
        , s.column2
        , s.column3
        , s.column4
        , s.column5, ....,
        , c.ParentID
    FROM
        ParentTable p WITH(NOLOCK)
        LEFT JOIN SomeOtherTable s WITH(NOLOCK) ON
            p.ID = s.ID
        LEFT JOIN ChildTable c WITH(NOLOCK) ON
            p.ID = c.ParentID

    WHERE
        p.CreatedDate >= @Date
    ORDER BY
        p.CreatedDate DESC;

END

This one is working fine, but is returning the value only for records which have a value in the child table. Also, the relation between parent-child is one-to-many. This query is also returning the same record from the parent table for every record in the child table, and it is only returning those records which have an entry in both tables, which shouldn't be the case.
Can anybody help me with how to do this? I'm using SQL Server.

A: Simply use exists in a case expression.
Select <columns from parent table>,
  case when exists (select * from ChildTable c where c.ParentId=p.Id) then 1 else 0 end as HasChild
from Parent t

I was about to also suggest a more compact form using iif() then noted you had tagged SQL Server 2008... so I won't!

A: Your query is obviously contrived to illustrate the issue, and not the actual query.  So this answer also uses contrived data to illustrate what it sounds like you want.
It seems like you are trying to return the record from ParentTable with a true or false to indicate if there is a record in the child table.

*

*You cannot LEFT JOIN at child table and then use the child table in the WHERE clause.  Doing so changes it to an INNER JOIN.

*If you have a one-to-many relationship and join the two tables together, you will see the parent record as many times as there are child records.

There are several ways to see if there is a child record.  These are but two solutions.  You should look at the query plan of whatever you choose to use, so that you can make sure it is optimized against your dataset.
create table #parent (id int, value varchar(10))
create table #child (id int, parent_id int, value varchar(10))

create clustered index pk_parent on #parent (id)
create clustered index pk_child on #child (id)
create index idx_fk_child_parent on #child (parent_id)

insert into #parent values (1, 'one'), (2, 'two'), (3, 'three')
insert into #child values (1, 1, 'red'), (2, 3, 'blue'), (3, 3, 'green')

/* correlated sub-query solution */
select p.*, has_child = cast(1 as bit)
from   #parent p
where  exists (select 1 from #child c where p.id = c.parent_id)

union all

select p.*, has_child = cast(0 as bit)
from   #parent p
where  not exists (select 1 from #child c where p.id = c.parent_id)
order by p.id

/* nested sub-query solution */
select p.*, has_child = isnull(c.has_child, 0)
from   #parent p
       left join (
         select distinct parent_id, has_child = cast(1 as bit)
         from   #child
       ) c on p.id = c.parent_id
order by p.id

drop table #parent, #child

Both of these return the following:
id          value      has_child
----------- ---------- ---------
1           one        1
2           two        0
3           three      1

The correlated sub-query is the most obvious and simply sets has_child to true or false based on exists or not exists.  The sub-query solution is less obvious.  If a record exists, has_child will be 1.  If a record does not exists, has_child will be NULL.
The sub-query performs better than the correlated sub-query because it only has to hit the tables 1 time each, instead of two times.  But I don't know how many records you actually have in your tables or how they are indexed.  So look at the query plan for both and see where you can optimize.
I added indexes that would approximate the indexes in a real database.  The cost of the correlated sub-query is 4 times higher than the sub-query solution.  Other solutions likely exist that would perform even better.
The nested sub-query solution has very good stats, the CPU is especially low in the inner query.
Hopefully this helps and answers your questions.


text:
Q: count number of a char array appeared in another char array the code should count number of a char array #1 appeared in another char array #2
but it keep adding one more count !!
public static int countSTR(char c1[], int c1Length, char c2[], int c2Length){
  int count=0;
  char last=c2[c2Length-1];
  for (int i=0;i<c1Length;i++)
     for (int j=0; j<c2Length;j++)

        if (c1[i]==c2[j])
              if(j+1==c2Length)
                 count++;

              else
                 continue;
  return count;
 }

arrays I tested :
char [] str = {'C','A','B','L','B','Y' ,'A','M','C','S','C'};
char []m={'M','C'};
the output : 3
it should be 1

A: Please try this:
public static int countSTR(char c1[], int c1Length, char c2[], int c2Length) {
    if (c1 == null || c2 == null || c1Length < 1 || c2Length < 1 || c1Length > c1.length || c2Length > c2.length)
        return 0;

    int count = 0;

    for (int i = 0; i <= c1Length - c2Length; i++)
        for (int j = 0; j < c2Length; j++)
            if (c1[i + j] == c2[j]) {
                if (j == c2Length - 1)
                    count++;
            } else
                break;
    return count;
}

A: I think you have overcomplicated the process. Just increment the count when they are equal. The for loops will continue, without using continue.
for (int i=0;i<c1Length;i++){
    for (int j=0; j<c2Length;j++){

        if (c1[i]==c2[j]){
            count++;
         }

    }
}
return count;

A: You need to only increase the counter if you have a complete match. This should do the job:
private void run() {
    char[] text = "foo bar foobar".toCharArray();
    char[] searchWord = "foo".toCharArray();
    System.out.println(countOccurrences(text, searchWord)); // prints 2
    text = new char[] { 'C', 'A', 'B', 'L', 'B', 'Y', 'A', 'M', 'C', 'S', 'C' };
    searchWord = new char[] { 'M', 'C' };
    System.out.println(countOccurrences(text, searchWord)); // prints 1
}

private int countOccurrences(char text[], char searchWord[]) {
    int counter = 0;
    for (int offset = 0; offset <= text.length - searchWord.length; offset++) {
        if (matchesAt(text, searchWord, offset)) {
            counter++;
        }
    }
    return counter;
}

private boolean matchesAt(char[] text, char[] searchWord, int offset) {
    for (int i = 0; i < searchWord.length; i++) {
        if (text[offset + i] != searchWord[i]) {
            return false;
        }
    }
    return true;
}

A: Here's an alternative using Java 8's stream API:
public static int countSTR(char[] c1, char[] c2)
{
    if(c1 == null || c2 == null || c1.length == 0 || c1.length > c2.length)
        return 0;

    long result = IntStream.range(0, c2.length - c1.length+1)
            .mapToObj(i -> IntStream.range(0, c1.length)
                    .mapToObj(j -> c2[i+j]).toArray())
            .filter(array -> IntStream.range(0, c1.length)
                    .mapToObj(i -> c1[i] == (char)array[i])
                    .allMatch(bool -> bool == true))
            .count();

    if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (result + " cannot be cast to int without changing its value.");
    }

    return (int)result;
}

Also, there's no need to pass an int with the length of the arrays as you would in C since you can get an array's length by accessing array.length.


text:
Q: RETURNING value from SELECT table in INSERT .. SELECT I have a table that looks like this:
| column | def  |
| ------ | ---- |
| id     | uuid |
| status | int  |
| data   | text |

I'd like to write a query to duplicate a row (changing only a few columns) and return the old (replaced) data:
INSERT INTO tmp (status, data)
SELECT source.status, :data
FROM table AS source
WHERE id = :id
RETURNING id, source.data

but RETURNING can only access values from the inserted row, is there an alternative to do this?

A: You can 'store' your old data in a CTE, then do the change in another (writable) CTE, and return the original values like this:
WITH old AS (
    SELECT status, data
      FROM your_table
     WHERE id = :id
),
new AS (
    INSERT INTO your_table
    SELECT status, :data
      FROM old
)
SELECT * FROM old;

The writable CTE (new) works on the results of the previous one (old).


text:
Q: Expected value of gradient bound proof I saw the following statement in a paper and couldnt find a proof anywhere.
Proposition 1.
Denote $\sigma^2= \mathbb{E}[\|\nabla f_{\xi}(x^*)\|^2]$
and assume $f$ to be almost surely $L$-smooth and convex. Then it holds for any $x$
$$
\mathbb{E}\left[\left\|\nabla f_{\xi}(x)\right\|^2\right] \leq 4 L\left(f(x)-f_*\right)+2 \sigma^2
$$
How do i prove this or where can i find a proof? It seems well known since it is just stated