text:
Q: Too many values to unpack during template rendering I am learning Django right now and I came across this error which I am a bit stumped on. I am trying to get my form onto the my homepage
I get this error:

code:
home/views.py:
from django.shortcuts import render
from forms import TestForm
from django.http import HttpResponseRedirect

def home(request):
    if request == 'POST':
        # create a form instane and populate it with data from the request
        form = TestForm(request.POST)
        if form.is_valid():
            # process the data in form.cleaned_data as required
            form.cleaned_data()
            # redirect to a new URL:
            return HttpResponseRedirect('/test/')
    # if a GET (or any other method) we'll create a blank form
    else:
        form = TestForm()
    return render(request, 'home/home_page.html', {'form': form})

def scan_events(request):
    if request == "POST":
        # json = request.POST['testData']
        # condition statement for file upload ot c/p events

        return render(request, 'home/test.html', {'data': request.POST})

def test(request):
    request(request, 'home/test.html')

home/forms.py
from django import forms

TEST_TYPE_CHOICES = ('HDFS', 'HIVE', 'BOTH')

class TestForm(forms.Form):
    # hdfs_test = forms.MultipleChoiceField()
    # hive_test = forms.MultipleChoiceField()
    # hdfs_hive_test = forms.MultipleChoiceField()
    test_type = forms.MultipleChoiceField(required=True, widget=forms.RadioSelect(), choices=TEST_TYPE_CHOICES)
    event_textarea = forms.Textarea(attrs={'rows': '8', 'class': 'form-control', 'placeholder': 'Events...', 'id': 'event_textarea'})
    # file_upload = forms.FileInput()

urls.py:
urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'home.views.home', name='home'),
    url(r'test/$', 'home.views.test'),

)

home/templates/home/home_page.html
{% extends 'index/index.html' %}

{% load staticfiles %}
{% block head %}

  <link href="{{ STATIC_URL }}home/css/home.css" rel="stylesheet">
{% endblock head %}

{% block content %}

Welcome to Trinity E2E testing

  <form id="test-form" action="/test/" method="post"> {# pass data to /test/ URL #}
    {% csrf_token %}

    {{ form }}

    <input id="submit-test" type="submit" class="btn btn-default btn-lg" value="Submit">
  </form>

{% endblock content %}

A: choices should be a sequence (iterable to be exact) of key-description pairs.
TEST_TYPE_CHOICES = [
    ('HDFS', 'HDFS'),
    ('HIVE', 'HIVE'),
    ('BOTH', 'Both of HDFS and HIVE'),
]

Explanation of the error message:
Strings are also sequences. So the code that use choices see the string as a sequence of 4 character (string to be exact, because there's no character type in Python). That's why you get the error: too many values to unpack
>>> a, b = ('HDFS', 'HDFS')
>>> a, b = 'HDFS'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: too many values to unpack

If the strings were all 2-character strings, it would hide (not solve) the problem.
>>> a, b = 'HD'
>>> a
'H'
>>> b
'D'


text:
Q: Why is the content being sorted by the wrong option? So I am grabbing movie info from an API. In my page, I have three options in a dropdown for sorting by Alphabet, User Score, and Popularity.
The problem is that when I choose an option it sorts by the option before it. For example, when I choose to sort by User Score, it sorts Alphabetically which is the option before it in the dropdown. And then if I keep choosing options it eventually becomes random and sorts with any of them.
Not sure why this is happening. I'm guessing it has something to do with how I'm setting the state.
Here's my code:
import React, {Component} from "react";
import {connect} from "react-redux";
import {crimeGenre} from "./redux";

class CrimeGenre extends Component {
    constructor(){
        super();

        this.state = {
            value: "alphabetically"
        }
    }

    componentDidMount(){
        this.props.crimeGenre();
    }

    sortFilms = (event) => {
        this.setState({
            value: event.target.value
        })
        if(this.state.value === "alphabetically"){
            return this.props.select && this.props.select.sort((a, b) => {
                return a.title  {
                return a.vote_average > b.vote_average ? -1 : 1;
            });
        }else if(this.state.value === "popularity"){
            return this.props.select && this.props.select.sort((a, b) => {
                return a.popularity > b.popularity? -1 : 1;
            });
        }
    }

    render(){
        const mappedSelected = this.props.select && this.props.select.map((film, i) => {
            return (

{film.title}

                    <img src={`http://image.tmdb.org/t/p/w185${film.poster_path}`}/>

Avg. User Score: {film.vote_average}

Popularity Index: {film.popularity.toFixed(0)}

            )
        })

            return(

                <form>

                        Sort By:
                        <select value={this.state.value} onChange={this.sortFilms}>
                            <option id="alphabetically" value="alphabetically">Alphabetically</option>
                            <option id="score" value="score">User Score</option>
                            <option id="popularity" value="popularity">Popularity</option>
                        </select>

                </form>
                    {mappedSelected}

            )
        }
    }

export default connect(state=> state, {crimeGenre})(CrimeGenre);

A: React's setState() does not immediately reflect the updation of the state value but creates a pending state transition. Accessing the state after calling setState() can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
Check out the official ReactJS Docs which explains this better.

To make sure your sortFilms function uses the new state, pass it as a callback of setState() like this:
sortFilms = (event) => {
    this.setState({value: event.target.value}, function () {
        if(this.state.value === "alphabetically"){
            return this.props.select && this.props.select.sort((a, b) => {
                return a.title  {
                return a.vote_average > b.vote_average ? -1 : 1;
            });
        }else if(this.state.value === "popularity"){
            return this.props.select && this.props.select.sort((a, b) => {
                return a.popularity > b.popularity? -1 : 1;
            });
        }
    });
}

A: There are a couple of things you need to change
First use your select prop to set your initial state like
 constructor(props){
        super(props);
        this.state = {
            value: "alphabetically",
            select: props.select
           }
        }

You want to do this because you want to cause a re-render whenever select changes(or its order changes) that is why it belongs to the state of your component.
Now coming to your sortFilm function set the state after you have sorted the values like :
sortFilms = event => {
  const sorter = event.target.value;
  const films = this.state.select;
  if (sorter === "alphabetically") {
    films.sort((a, b) => {
      return a.title  {
      return a.vote_average > b.vote_average ? -1 : 1;
    });
  } else if (sorter === "popularity") {
    films.sort((a, b) => {
      return a.popularity > b.popularity ? -1 : 1;
    });
  }
  //Now we set the state to cause the re-render
  this.setState({ value: sorter, select: films });
};

And finally to consume our state that changes whenever we filer we will use our state instead of props like
const mappedSelected = this.state.select && this.state.select.map((film, i) => {
            return (

{film.title}

                    <img src={`http://image.tmdb.org/t/p/w185${film.poster_path}`}/>

Avg. User Score: {film.vote_average}

Popularity Index: {film.popularity.toFixed(0)}

            )
        })

Now coming to the problem with your code :
You are setting the state that causes a render and is async so when you change your props by sorting them there is no way for the component to know that the props are changed. So, when ever the next re-render is caused it the component updates and starts using the new props, This starts to behave randomly when you start changing the filters quickly as it changes the props multiple times even before the state is set.
The code from AndrewL fails for a similar reason, it sets the state and causes a re-render and then changes the props, the component doesn't have the new prop to update itself there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove Intel push-pin heatsink from motherboard? I have an Intel E29477 heatsink with those push-pin quarter turn fasteners in the corners.  I just replaced my motherboard and apparently didn't get the thermal compound on right when installing the heatsink on the new motherboard.
I've been trying to remove the heatsink to reapply the thermal compound, but it won't budge.  The little black tab just won't come up on two of the four fasteners.  I've yanked on it pretty hard with pliers and it stays put.

I've already done this once when removing from the old motherboard, so it's not that I forgot to turn the tabs.  This is one of the tabs in question: I'm pretty sure I've got it turned the right way.

Is there anything I can do short of breaking the white tabs off and buying a new heat sink?
.

A: You need to turn them in the direction of the arrow (ant-clockwise), then pull up on them. It's a bit hard to see in the underside picture if it's currently locked in or not. If you still can't get them to come out try pinching the underside of the pins with some pliers while pulling them out.

A:
To remove the fan/heatsink assembly:

*

*Using a screwdriver in the slot on the "shelf" atop the actuator, rotate each of the four actuators counterclockwise (in the direction of the arrow).  That unlocks the PPL.

*Then, one-by-one, pull up on each actuator, retracting the black central pin from the split pin, allowing them to slip back through the motherboard holes.
Pull up (gently) with a rocking motion to free the fan/heatsink assembly from the motherboard and the CPU.

Source See post by CAOgdin


text:
Q: How to set the displayed precision for a complex number in Excel 2010? MS Excel provides a set of functions to work with complex numbers. When displaying real numbers, one can set the decimal places precision from the Format Cells dialog. However, it does not work for complex numbers.
How can I set the displayed precision of a complex number? Is there a custom template I can use for that?
0.98078528040323+0.195090322016128i --> 0.980+0.195i

A: To achieve this by formula (in a different cell), you can use the following, where your unformatted complex number is in A1:
=COMPLEX(VALUE(TEXT(IMREAL(A1),"0.000")),VALUE(TEXT(IMAGINARY(A1),"0.000")))

A: You could wrap your complex formula's in a UDF that does the formatting:
Function FormatComplex(r As Variant, fmt As String) As String
    With Application.WorksheetFunction
        FormatComplex = Format(.ImReal(r), fmt) & Format(.Imaginary(r), fmt) & "i"
    End With
End Function

Call it like
=FormatComplex(IMSQRT(-2),"+0.000")

result:
+0.000+1.414i


text:
Q: AWS Lambda de-serializer / LinkedHashmap cannot cast I'm new to Java/AWS etc., and AWS lambda we not de-serialize what I think is a trivial example.
The API Gateway log, which is sending JSON to my lambda:

Execution log for request test-request
  Mon Sep 11 18:04:06 UTC 2017 : Starting execution for request: test-invoke-request
  Mon Sep 11 18:04:06 UTC 2017 : HTTP Method: POST, Resource Path: /
  Mon Sep 11 18:04:06 UTC 2017 : Method request path: {}
  Mon Sep 11 18:04:06 UTC 2017 : Method request query string: {}
  Mon Sep 11 18:04:06 UTC 2017 : Method request headers: {Content-Type=application/json}
  Mon Sep 11 18:04:06 UTC 2017 : Method request body before transformations: {"input":"richard was here"}
  Mon Sep 11 18:04:06 UTC 2017 : Endpoint request URI: https://lambda.us-west-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-west-2:003374398906:function:uppertolowercase/invocations
  Mon Sep 11 18:04:06 UTC 2017 : Endpoint request headers: {x-amzn-lambda-integration-tag=test-request, Authorization=****************************************************************************************************************************************************************************************************************************************************************************************************************************************8acc24, X-Amz-Date=20170911T180406Z, x-amzn-apigateway-api-id=8fjgcr51va, X-Amz-Source-Arn=arn:aws:execute-api:us-west-2:003374398906:8fjgcr51va/null/POST/, Accept=application/json, User-Agent=AmazonAPIGateway_8fjgcr51va, X-Amz-Security-Token=xxxxxxx//////////wEaDM3BrDjbuGSwMFT5lCK3AyBVM7duW9tzEe/bcWqWiYNIxkpMjTdDZaW3U32asJ4qvntUsRpjfSIhLWAds74XhzHbI7GzXMuV3zQYCIiYRX0ZL1s524J7mETGFN4OredlGln7CCEs3WR417UaPB4XLh6E0v71Srpg4a1kG7KB6426gN9CvXR0mmYbwpl9qtp9bovLgIoVnjYbx5j7qd7Fa3U4wQOqcHonlKtN/uDXMFW+vfHOJyu3gQUyvoVpMuXrQSF/gptEXG+l0v4+v1exq67sp8G5d8h1kAQTNQep8Q19kyOi9hWbNDyU7FzXWvfSRX7f9n6NGIuZ6LYIF3g2kPFY [TRUNCATED]
  Mon Sep 11 18:04:06 UTC 2017 : Endpoint request body after transformations: {"input":"richard was here"}
  Mon Sep 11 18:04:06 UTC 2017 : Sending request to https://lambda.us-west-2.amazonaws.com/2015-03-31/functions/arn:aws:lambda:us-west-2:003374398906:function:uppertolowercase/invocations
  Mon Sep 11 18:04:06 UTC 2017 : Received response. Integration latency: 73 ms
  Mon Sep 11 18:04:06 UTC 2017 : Endpoint response body before transformations: {"errorMessage":"java.util.LinkedHashMap cannot be cast to com.morethanheroic.uppercase.domain.UppercaseRequest","errorType":"java.lang.ClassCastException","stackTrace":["com.morethanheroic.uppercase.UppercaseFunction.apply(UppercaseFunction.java:13)","org.springframework.cloud.function.support.FluxFunction.lambda$apply$0(FluxFunction.java:42)","reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:107)","reactor.core.publisher.FluxJust$WeakScalarSubscription.request(FluxJust.java:90)","reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request(FluxMapFuseable.java:159)","reactor.core.publisher.BlockingIterable$SubscriberIterator.onSubscribe(BlockingIterable.java:214)","reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe(FluxMapFuseable.java:90)","reactor.core.publisher.FluxJust.subscribe(FluxJust.java:67)","reactor.core.publisher.FluxMapFuseable.subscribe(FluxMapFuseable.java:63)","reactor.core.pu [TRUNCATED]
  Mon Sep 11 18:04:06 UTC 2017 : Endpoint response headers: {x-amzn-Remapped-Content-Length=0, x-amzn-RequestId=9a0ca35b-971b-11e7-b0d0-653f3fe89968, Connection=keep-alive, Content-Length=1557, X-Amz-Function-Error=Unhandled, Date=Mon, 11 Sep 2017 18:04:05 GMT, X-Amzn-Trace-Id=root=1-59b6d016-3a1ae0e3274a3e84e451bf13;sampled=0, Content-Type=application/json}
  Mon Sep 11 18:04:06 UTC 2017 : Method response body after transformations: {"errorMessage":"java.util.LinkedHashMap cannot be cast to com.morethanheroic.uppercase.domain.UppercaseRequest","errorType":"java.lang.ClassCastException","stackTrace":["com.morethanheroic.uppercase.UppercaseFunction.apply(UppercaseFunction.java:13)","org.springframework.cloud.function.support.FluxFunction.lambda$apply$0(FluxFunction.java:42)","reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onNext(FluxMapFuseable.java:107)","reactor.core.publisher.FluxJust$WeakScalarSubscription.request(FluxJust.java:90)","reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.request(FluxMapFuseable.java:159)","reactor.core.publisher.BlockingIterable$SubscriberIterator.onSubscribe(BlockingIterable.java:214)","reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onSubscribe(FluxMapFuseable.java:90)","reactor.core.publisher.FluxJust.subscribe(FluxJust.java:67)","reactor.core.publisher.FluxMapFuseable.subscribe(FluxMapFuseable.java:63)","reactor.core.publi [TRUNCATED]
  Mon Sep 11 18:04:06 UTC 2017 : Method response headers: {X-Amzn-Trace-Id=sampled=0;root=1-59b6d016-3a1ae0e3274a3e84e451bf13, Content-Type=application/json}
  Mon Sep 11 18:04:06 UTC 2017 : Successfully completed execution
  Mon Sep 11 18:04:06 UTC 2017 : Method completed with status: 200

I'm using this JSON to provide data to be de-serialized to  the following POJO
 {"input":"richard was here"}

public class UppercaseRequest {

    private String input;

    public String getInput() {
        return input;
    }

    public void setInput(final String input) {
        this.input = input;
    }
}

Here is the handler
public class UppercaseFunctionHandler extends SpringBootRequestHandler<UppercaseRequest, UppercaseResponse> {
}

NOTE: taken from sample project from
https://github.com/laxika/spring-cloud-function-aws-example
It's not documented in the example - but the Lambda entry point that I used is:

com.morethanheroic.uppercase.handler.aws.UppercaseFunctionHandler::handleRequest

A: It works for me if I specify the handler in the right way (com.morethanheroic.uppercase.handler.aws.UppercaseFunctionHandler in this case):
{
  "result": "FOO"
}

I think the mistake was the handler declaration in the AWS console. You have to put the FQN of the class (not a method reference). The method does not have the generic type information, unless you override it (which you said worked as well, but is unnecesasary).
The OP made a screencast of himself deploying and testing the function (https://www.screencast.com/t/mNOLS1XhM), which is almost all perfect except the handler name.
The code is here if anyone else wants to try it: https://github.com/laxika/spring-cloud-function-aws-example.


text:
Q: How to make SQL parse this XML faster The code below works but it takes 16 minutes to parse the XML from 36,000+ rows in SQL. Is there a way I could change the below code to make it parse the XML faster? I have updated the code below.
select c.claimid, c.adjuddate as lastadjudication, cast(claimedithistory as xml) as xmldata, ca.adjudicationattempts into #kb from claimedithistory ca (nolock) join claim c (nolock) on ca.claimid = c.claimid  where adjuddate > dateadd(d, 1, eomonth(getdate(), -3)) order by c.claimid

alter table #kb add primary key (claimid, adjudicationattempts)

create table #kb2 (claimid char(15) not null,lastadjudication Date not null,attempt int not null, id char(60) null, adjuddate date null)

Declare @claimid char(15)
Declare @lastadjudication as date
declare @xmldata as xml
declare @adjudicationattempts as int
declare @nextadjudication as int
set @nextadjudication = 1

SET NOCOUNT ON

DECLARE db_cursor CURSOR FOR
SELECT claimid, lastadjudication, xmldata, adjudicationattempts
FROM #kb order by claimid desc

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @claimid, @lastadjudication, @xmldata, @adjudicationattempts

WHILE @@FETCH_STATUS = 0
BEGIN

    set @nextadjudication = 1
    WHILE @nextadjudication <= @adjudicationattempts
            BEGIN

                insert into #kb2 (claimid, lastadjudication, attempt, id, adjuddate)
                select claimid, lastadjudication,xmldata.value('(ClaimEditHistory[sql:variable("@nextadjudication")]/@attempt)[1]', 'int')  as attempt,
                xmldata.value('(ClaimEditHistory[sql:variable("@nextadjudication")]/@userid)[1]', 'varchar(15)')  as id,
                xmldata.value('(ClaimEditHistory[sql:variable("@nextadjudication")]/@datetime)[1]', 'datetime')  as adjuddate
                from #kb
                where claimid = @claimid
                    and xmldata.value('(ClaimEditHistory[sql:variable("@nextadjudication")]/@datetime)[1]', 'datetime') > dateadd(d, 1, eomonth(getdate(), -3))
                    and xmldata.value('(ClaimEditHistory[sql:variable("@nextadjudication")]/@userid)[1]', 'varchar(15)') <> 'hsnprbatch'
                    and xmldata.value('(ClaimEditHistory[sql:variable("@nextadjudication")]/@userid)[1]', 'varchar(15)') <> 'TorresM'
                set @nextadjudication = @nextadjudication + 1
            END

      FETCH NEXT FROM db_cursor INTO @claimid, @lastadjudication, @xmldata, @adjudicationattempts
END

CLOSE db_cursor
DEALLOCATE db_cursor

select * from #kb2

A: Why don't you just create an SSIS package that runs this in 3-4 parts (instead of one) whenever you need it and dump it into a SQL table? Then just call the table, it will be much faster than trying to do it all in a query like that.


text:
Q: How to write select query if the condition contains single quotes(') I Want to retrive the data from Oracle DB where name contins single quote(')
Select * from table_name where name in ('Joel D'Silva','O'neil Dsa');

A: You could pass string to q'[]' in following:
Select * from table_name where name in (q'[Joel D'Silva','O'neil Dsa]');

or you could use quote ' twice in following:
Select * from table_name where name in ('Joel D''Silva'',''O''neil Dsa');

A: Replace ' with '':
Select * from table_name where name in ('Joel D''Silva','O''neil Dsa');


text:
Q: Check if a relation is completly inside an area I wanted to get all federal states in Germany via Overpass. With this query I get almost the desired result:
[out:json];

relation(51477);
map_to_area -> .germany;
relation(area.germany)["type"="boundary"]["boundary"="administrative"]["admin_level"="4"];

out tags;

https://overpass-turbo.eu/s/1alL
Unfortunately one of the results is not a German federal state: Groningen
Groningen is actually an area in the Netherlands, but because of the border parts are within German territory.
To fix this result, I thought check if each relation is completly in the territory of Germany. But I'm quite new to Overpass and the syntax is a bit complicated to understand.
Any idea if this is possible? Or is it even a bug that OVerpass returns Groningen even though only a part of it is inside of Germany (according to OpenStreetMap data)?


text:
Q: import of keras and tensorflow seems to break pycharm I'm facing a weird issue.
I'm working in Pycharm IDE and I want to use keras with tensorflow backend.
When I try to import keras or tensorflow pycharm process finished with exit code -1073741819 (0xC0000005).
For example
import tensorflow as tf
n_input = 2
print (n_input)

returns message described above without printing anything.
If i comment the tf import it works.
Keras and tensorflow are correctly installed under the python interpreter of my choice.
I'm on windows machine, Python 3.6.8
Thanks


text:
Q: LINQ statement only resulting one result on a DataTable where multiple exist I have a DataTable that is populated from a database as follows:
SPName      SName   Row  text
p_obj_prod1 dbo     1    A
p_obj_prod1 dbo     1    B
p_obj_prod1 dbo     1    C
p_obj_prod2 dbo     1    D
p_obj_prod2 dbo     1    E
p_rpt_prod3 dbo     1    F
p_rpt_prod3 dbo     1    G
p_rpt_prod3 dbo     1    H

And I have the following code that will process this data:
foreach (var row in procedureData.Tables[0].AsEnumerable()
    .Select(dr => new { Schema = dr["SName"], Procedure = dr["SPName"] })
    .Distinct())
{
     //DO STUFF
     foreach (string procedureText in procedureData.Tables[0].AsEnumerable()
         .Where(dr => dr["SPName"] == row.Procedure).Select(dr => dr["text"]))
     {
          //DO MORE STUFF
     }
     //DO EVEN MORE STUFF
 }

In this case I would expect the outer foreach loop to iterate 3 times, and it does. I would also expect that the inner foreach loop would iterate 3 times for the first outer loop iteration, 2 times for the second and 3 times for the third. However the inner loop only ever has one value (the first one in the sequence).
I'm not new to LINQ and have create far more complex queries than this, but this one really has me stumped on the reason why the inner loop doesn't have all the expected results. I guess I have made a mistake in the second loop's LINQ query, but it seems fine to me.
Can anyone shed some light on what might be the issue?
Thanks very much.
UPDATE
Just realised the mistake I was making and why the inner loop only had one value. It was because it was doing a reference comparison, not a value comparison on the 'SPName' column of the DataTable.
Changing the inner loop's code to the following fixed the issue, however I will keep the GroupBy version as I prefer it!
foreach (string procedureText in procedureData.Tables[0].AsEnumerable()
         .Where(dr => dr["SPName"].ToString() == row.Procedure.ToString())
         .Select(dr => dr["text"]))
     {

A: Why not just use a GroupBy:
var grouped = procedureData.Tables[0]
                           .AsEnumerable()
                           .GroupBy(dr=>new
                           {
                                Schema = dr["SName"],
                                Procedure = dr["SPName"]
                           });

foreach(var g in grouped)
{
    //DO STUFF
    foreach(string procedureText in g.Select(dr => dr["text"]))
    {
        //DO MORE STUFF
    }
    //DO EVEN MORE STUFF
}

Otherwise, I don't see what's wrong with your code. It works fine for me.


text:
Q: React Native Google / Facebook Login I'm quit new in React native but I would like to set up Google login but what I did didn't seem to work.
(That will be a long post haha )
For Google Login:
I tried several tutorials on YouTube (this one for example: https://www.youtube.com/watch?v=DN9dQ_6ezvA)

"Request is missing required authentication credential. Expected OAuth
2 access token, login cookie or other valid authentication credential.
See
https://developers.google.com/identity/sign-in/web/devconsole-project."

I tried a lot of thing but it's really hard for me. So if someone could give me some help? Thanks you in advance guys, I continue the research on my side
Here is my code:
WebBrowser.maybeCompleteAuthSession();

export default function GoogleFunc({largeur}) {
  const fontRegular = require("../../assets/Manrope-Regular.ttf");
  const fontBold = require("../../assets/Manrope-Bold.ttf");

  const [fontsLoaded] = useFonts({
    ManropeRegular: fontRegular,
    ManropeBold: fontBold,
  });

  const [accessToken, setAccessToken] = React.useState();
  const [userInfo, setUserInfo] = React.useState();
  const [request, response, prompAsync] = Google.useIdTokenAuthRequest({
    androidClientId:
      "ANDROID_CLIENT_ID",
    iosClientId:
      "CLIENT_CLIENT_ID",
    clientId:
      "CLIENT_ID",
  });

  React.useEffect(() => {
    if (response?.type === "success") {
      console.log("response: ", response.params);
      setAccessToken(response.params.id_token);
      accessToken && fetchUserInfo();
    }
  }, [response, accessToken]);

  async function fetchUserInfo() {
    console.log("test222");
    let response = await fetch("https://www.googleapis.com/userinfo/v2/me", {
      headers: {Authorization: `Bearer ${accessToken}`},
    });
    const useInfo = await response.json();
    console.log("useinfo: ", useInfo);
    setUserInfo(useInfo);
  }

  const ShowUserInfo = () => {
    if (userInfo) {
      console.log("userinfooofofof: ", userInfo);
      return (
        <View style={styles.userInfo}>
          <Image source={{uri: userInfo.picture}} style={styles.profilePic} />
          <Text>Welcome {userInfo.name}</Text>
          <Text>{userInfo.email}</Text>
        </View>
      );
    }
  };

  return (
    <View style={styles.container}>
      {userInfo && <ShowUserInfo />}
      {userInfo == null && (
        <>
          <TouchableOpacity
            style={[styles.googleBtn, {width: largeur}]}
            disabled={!request}
            onPress={() => {
              prompAsync();
            }}
          >
            <Image
              style={{
                height: height * 0.024,
                width: width * 0.057,
                left: width * 0.035,
                top: height * 0.013,
              }}
              source={require("../../assets/images/google-logo.png")}
            />
            <Text
              style={{
                textAlign: "center",
                fontFamily: "ManropeSemiBold",
                fontSize: 17,
                color: "#262626",
                bottom: height * 0.01,
              }}
            >
              Continuer avec Google
            </Text>
          </TouchableOpacity>
        </>
      )}
    </View>
  );
}

For Facebook:
I tried to set up the login with / without firebase but I already got the same issue : an error ...
I'm trying to solve it since last week but I don't understand how can i fix these problems ...
Here's my code without Firebase:
import React, {useState} from "react";
import {
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  ActivityIndicator,
} from "react-native";
import * as Facebook from "expo-facebook";

export default function FacebookFunc() {
  const [isLoggedin, setLoggedinStatus] = useState(false);
  const [userData, setUserData] = useState(null);
  const [isImageLoading, setImageLoadStatus] = useState(false);

  async function faceookLogIn() {
    try {
      await Facebook.initializeAsync({
        appId: "APP ID",
      });
      const {type, token, expirationDate, permissions, declinedPermissions} =
        await Facebook.logInWithReadPermissionsAsync({
          permissions: ["public_profile"],
        });
      if (type === "success") {
        // Get the user's name using Facebook's Graph API
        const response = await fetch(
          `https://graph.facebook.com/me?access_token=${token}`
        );
        Alert.alert("Logged in!", `Hi ${(await response.json()).name}!`);
      } else {
        // type === 'cancel'
      }
    } catch ({message}) {
      alert(`Facebook Login Error: ${message}`);
    }
  }

  logout = () => {
    setLoggedinStatus(false);
    setUserData(null);
    setImageLoadStatus(false);
  };

  return isLoggedin ? (
    userData ? (
      <View style={styles.container}>
        <Image
          style={{width: 200, height: 200, borderRadius: 50}}
          source={{uri: userData.picture.data.url}}
          onLoadEnd={() => setImageLoadStatus(true)}
          // GERER QUAND MARCHERA
        />
        <ActivityIndicator
          size={"large"}
          color={"#0000ff"}
          animating={!isImageLoading}
          style={{position: "absolute"}}
        />
        <Text style={{fontSize: 22, marginVertical: 10}}>
          Hi {userData.name}!
        </Text>
        <TouchableOpacity style={styles.logoutBtn} onPress={logout}>
          <Text style={{color: "#fff"}}>Logout</Text>
        </TouchableOpacity>
      </View>
    ) : null
  ) : (
    <View style={styles.container}>
      <TouchableOpacity style={styles.loginBtn} onPress={faceookLogIn}>
        <Text style={{color: "#fff", textAlign: "center"}}>
          Login with facebook
        </Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {},
  loginBtn: {
    backgroundColor: "#4267b2",
    paddingVertical: 10,
    borderRadius: 10,
    width: "95%",
  },
  logoutBtn: {
    backgroundColor: "grey",
    includeFontPadding: 10,
    paddingHorizontal: 20,
    borderRadius: 20,
    position: "absolute:",
    bottom: 0,
    marginBottom: 200,
  },
});

And here my code when I trying with Firebase:
The error:

Possible Unhandled Promise Rejection (id: 0):
TypeError: null is not an object (evaluating 'LoginManager.logInWithPermissions')

The code:
import React from "react";
import {LoginManager, AccessToken} from "react-native-fbsdk-next";
import {
  StyleSheet,
  View,
  Text,
  Image,
  TouchableOpacity,
  Button,
} from "react-native";
import {
  getAuth,
  signInWithCredential,
  FacebookAuthProvider,
} from "firebase/auth";
import "expo-dev-client";

import app from "./firebaseSetup";

export default function App() {
  const SignInWithFB = async () => {
    const result = await LoginManager.logInWithPermissions([
      "public_profile",
      "email",
    ]);
    if (result.isCancelled) {
      throw new Error("User cancelled login");
    }
    const data = await AccessToken.getCurrentAccessToken();
    if (!data) {
      throw new Error("Something went wrong obtaining access token");
    }
    const auth = getAuth(app);

    const credential = FacebookAuthProvider.credential(data.accessToken);
    const user = await signInWithCredential(auth, credential);
    console.log(user);
  };

  return (
    <View>
      <Button title="Sign in with facebook" onPress={SignInWithFB}></Button>
    </View>
  );
}

const styles = StyleSheet.create({});

I initialize my firebaseSetup like this:
import {initializeApp} from "firebase/app";

// Initialize Firebase
const firebaseConfig = {
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: "",
};

const app = initializeApp(firebaseConfig);
export default app;

I continue my research by my side but if someone could help me with this problem (which is probably stupid), thanks you in advance...
PS: There is the error for Facebook without firebase:

Facebook Login Error: undefined is not an object (evaluating'_ExponentFacebook.default.InitializeAsync')

A: You have to use expo auth session to implement oAuth in Expo
import React,{useState} from 'react';
import { useNavigation } from "@react-navigation/native";
import Fontisto from '@expo/vector-icons/Fontisto';
import { TouchableOpacity,StyleSheet, Alert } from 'react-native';
import * as WebBrowser from 'expo-web-browser';
import * as Facebook from 'expo-auth-session/providers/facebook';
import {makeRedirectUri, ResponseType } from 'expo-auth-session';
import { useDispatch } from "react-redux";

WebBrowser.maybeCompleteAuthSession();

export default function FacebookAuth(){

  const [isLoading, setIsLoading] = useState(false);
  const navigation = useNavigation();
  const dispatch = useDispatch();

      const [request, response, promptAsync] = Facebook.useAuthRequest({
        responseType: ResponseType.Token,
        clientId: 'YOUR_CLIENT_ID',
        scopes: ['public_profile', 'email'],
        redirectUri: makeRedirectUri({ useProxy: true })
      },
      { useProxy: true });

      React.useEffect(() => {
        if (response?.type === 'success') {
          setIsLoading(true);
          const accessToken = response.authentication.accessToken;

        console.log(accessToken);
        }
      }, [response]);

    return(
      <>
        <TouchableOpacity disabled={!request} style={styles.socialLoginButton}
        onPress={() => {
            promptAsync();
          }}
        >
             <Fontisto name='facebook' color={'white'} size={25}/>
        </TouchableOpacity>
      </>
    )
}

const styles = StyleSheet.create({
    socialLoginButton:{
        margin:3,
        backgroundColor:'blue',
        padding:10,
        borderRadius:50,
        width:50,
        height:50,
        justifyContent:'center',
        alignItems:'center',
        margin:10,
      }
})

Here's the code for it, you have to configure it according to your needs.
here's the link for expo auth session. - here

A: For login with Google, I think the problem lies with this code:
 React.useEffect(() => {
    if (response?.type === "success") {
      setAccessToken(response.params.id_token);
      accessToken && fetchUserInfo();
    }
  }, [response, accessToken]);

You use the id_token from the response, and you should be using the access token. Also, I think you could split this into two useEffect methods:
 React.useEffect(() => {
    if (response?.type === "success") {
      setAccessToken(response.params.access_token);
    }
  }, [response]);

 React.useEffect(() => {
      fetchUserInfo();
 }, [accessToken]);

The other effect will trigger only when the state of accessToken changes. If it's possible that you change the state to an empty value then you should retain the null check.
As for Facebook and Firebase issues — are you sure you followed all the required setup for these libraries? Just skimming through the documentation shows that there are quite a few things that should be configured before you can call the libs. From your error messages, it seems that the libraries are not configured and initialized properly.


text:
Q: Accepting empty strings in C My program can either accept a number of any length or empty input. However, if the input is empty (space or newline), the program continues to wait for an input. I also tried fgets but if space/newline is pressed, it still waits for more input that is not a space/newline before closing.
Simpified code:
#include <stdio.h>
main()
{
    int num;
    scanf("%i",&num);
    printf("%i",num);
}

Input:
363792

Output:
363792

Desired:
Input:
Output:
I'm new to C and am having a very hard time accomplishing this.
What tried using fgets:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
    int n;
    char s[20];

    fgets(s,20,stdin);
    n = atoi(s);

    printf("%i",n);
}

Edit: Turns out I was not compiling the code right. So every time I tried to make changes, it just looked at the original code using scanf.

A: According to definition of scanf()

The function will read and ignore any whitespace characters encountered before the next non-whitespace character.

So you can not get your desired result using scanf().
As gets()  is not safe and it misbehaves badly. you can use fgets() to get input and convert it to integer if you need using atoi().
Here sample code you can try:
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
main()
{
    int num;
    char ch[100];
    fgets(ch, sizeof ch, stdin);
    if (strlen(ch)>1&& ch[strlen(ch)-1] == '\n')
    {
        ch[strlen(ch)-1] = '\0';
        num = atoi(ch);
        printf("%i\n", num);
    }
}

A: You should read the input character by character and stop reading if the read character is not a number:
char ch;
while(1)
{
    ch=getchar();
    if(isdigit(ch))
    {
        putchar(ch);
    }
    else
    {
        break;
    }
}

A:
I also tried fgets but if space/newline is pressed, it still waits for more input that is not a space/newline before closing.

Firstly fgets will work in this case. If you had shown us what exactly you tried to do using fgets() then answer to this question would have much narrow or very specific.
I tried to do the same using fgets() and below is the code snippet.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
    char string[100];
    printf("Enter a number: ");

    fgets (string, 100, stdin);
    /* Here remove  the trailing new line char; not required unless you are trying to print the string */
    string[strlen(string) - 1] = '\0';

    printf("Num is %d\n", atoi(string));

    return 0;
}

If there is no input or just enter or space and enter, then number printed will be zero and fgets() will not wait until you enter a valid number.
Also check this on why you shouldn't use gets. Do not use gets()

A: alright, you do not understand what scanf() does, it goes and scans entire input string and looks for special characters like %d, %f, %s and until it does not get what is in string it will wait.
scanf("%d %d", a, b);

will get done only when you enter 2 integer values, if you press space it does not count as integer value so it will ignore it.


text:
Q: callback is not a function in sqlite i tried to make class DATABASE to create db.run to the reusable method to call for create update and delete in SQLite by the callback,
here is my code

const db = new sqlite3.Database("database.db", err => {
  if (err) {
    console.log(`can;t connected tp database, status: ${err}`);
  } else {
    console.log(`gotcha, succesfully connect to the database`);
  }
});

class DATABASE {
  static run(sql, params = [], callback) {
    db.run(sql, params, function(err) {
      if (err) {
        throw err;
        console.log(`something wrong with this ${sql}`);
        console.log(err);
        callback(err);
      } else {
        callback({"id" : this.lastID}) // this is could be null also
        console.log("sucesfully fo this ", sql);
      }
    });
  }
}

module.exports = DATABASE;

then i call that class by something like this:
const DATABASE = require("./setup.js");
const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database("database.db", err => {
  if (err) {
    console.log(`can;t connected tp database, status: ${err}`);
  } else {
    console.log(`gotcha, succesfully connect to the database`);
  }
});

db.serialize(() => {
  const departement = `CREATE TABLE IF NOT EXISTS departement(
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name TEXT NOT NULL,
                      city TEXT
                      )`;

  const employee = `CREATE TABLE IF NOT EXISTS employee(
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    firstName TEXT NOT NULL,
                    lastName TEXT,
                    gender TEXT NOT NULL CHECK (gender IN ('Male', 'Female')),
                    email TEXT NOT NULL UNIQUE ,
                    phone TEXT,
                    dept_id INTEGER,
                    FOREIGN KEY (dept_id) REFERENCES departement(id)
                    )`;
  DATABASE.run(departement);
  DATABASE.run(employee);

  // , err => {
  //   if (err) throw new Erro(`bugs here`);
  //   else console.log("sucess.....");
  // });
});

you can see the else statement, callback({this.lastID}) when i comment that and delete the else statement, it was successful to create the table,
but if I write that else statement again, the error message is CALLBACK IS NOT FUNCTION
but create table was successfully
the meaning this.lastId is the way sqlite3 gives this info is it puts a field on the 'this' object within the context of the run(SQL, [params], function(err) { this.lastID }) callback function ... but, only for times when run is called with an INSERT statement. Otherwise, its just 0 as this tutorial said https://stackabuse.com/a-sqlite-tutorial-with-node-js/
did you think my callback is incorrect ??

A: The issue is in the way you have written callback({this.lastID}) change it to callback(this.lastID) or callback({"lastID" : this.lastID}).
`const DATABASE = require("./setup");
const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database("database.db", err => {
  if (err) {
    console.log(`can;t connected tp database, status: ${err}`);
  } else {
    console.log(`gotcha, succesfully connect to the database`);
  }
});
var abc= function(arg){
  console.log(arg);
};

db.serialize(() => {
  const departement = `CREATE TABLE IF NOT EXISTS departement(
                      id INTEGER PRIMARY KEY AUTOINCREMENT,
                      name TEXT NOT NULL,
                      city TEXT
                      )`;

  const employee = `CREATE TABLE IF NOT EXISTS employee(
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    firstName TEXT NOT NULL,
                    lastName TEXT,
                    gender TEXT NOT NULL CHECK (gender IN ('Male', 'Female')),
                    email TEXT NOT NULL UNIQUE ,
                    phone TEXT,
                    dept_id INTEGER,
                    FOREIGN KEY (dept_id) REFERENCES departement(id)
                    )`;
  DATABASE.run(departement, abc);
  DATABASE.run(employee, abc);

  // , err => {
  //   if (err) throw new Erro(`bugs here`);
  //   else console.log("sucess.....");
  // });
});`

And you setup.js
const sqlite3 = require("sqlite3").verbose();
const db = new sqlite3.Database("database.db", err => {
  if (err) {
    console.log(`can;t connected tp database, status: ${err}`);
  } else {
    console.log(`gotcha, succesfully connect to the database`);
  }
});

class DATABASE {
  static run(sql, callback) {
    db.run(sql, function(err) {
      if (err) {
        throw err;
        console.log(`something wrong with this ${sql}`);
        console.log(err);
        callback(err);
      } else {
        callback(this.lastID) // this is could be null also
        console.log("sucesfully fo this ", sql);
      }
    });
  }
}

module.exports = DATABASE;


text:
Q: What is the TSQL syntax for selecting rows BETWEEN DateTime values I have data in 5-minute intervals with 24-hour roll-overs, like so:
LogTime
-------------
7/1/2017 7:01
7/1/2017 7:06
7/1/2017 7:11
7/1/2017 7:16
...
7/2/2017 6:56

I need a TSQL query to select all rows for a given date, e.g. entries from 07/02 00:00:00 through 07/02 06:59:59 are considered to be part of 07/01's data.
I'm using this query in SSMS' editor pane:
SELECT * FROM [LogEntries] WHERE [LogTime] BETWEEN '20170701 06:59:59' AND '20170702 07:00'

The problem here is that the strings need to be logically constructed from DateTime values.
Can this be done in a single query statement with passed-in DateTime parameters? I'm doing this for an SSRS report and I'd rather not resort to a Stored Procedure if I don't have to.

A: The question states "The problem here is that the strings need to be logically constructed from DateTime values".
In the BETWEEN (Transact-sql) documentation cited by the OP, example D (for datetimes) says this:

D. Using BETWEEN with datetime values
The following example retrieves rows in which datetime values are between '20011212' and '20020105', inclusive.
SELECT BusinessEntityID, RateChangeDate
  FROM HumanResources.EmployeePayHistory
  WHERE RateChangeDate BETWEEN '20011212' AND '20020105';

This makes it seem that the DateTime values needs to be supplied as strings. They don't. You can use datetimes.
Zohar's answer addresses the time-shifting part of the problem.

A: The simplest solution (though not sargable, so it might not be the best) is simply to subtract 7 hours from your LogTime values:
DECLARE @DateTime DateTime = GETDATE();

SELECT *
FROM [LogEntries]
WHERE CAST(DATEADD(HOUR, -7, [LogTime]) AS DATE) = CAST(@DateTime AS DATE);

A sargable solution is a little more cumbersome, but still quite easy:
SELECT *
FROM [LogEntries]
                   -- 07 am on the date of the @DateTime variable
WHERE [LogTime] >= CAST(CAST(@DateTime AS DATE) As DateTime) + CAST('00:07:00' As DateTime)
                 -- 07 am one day after the date of the @DateTime variable
AND  [LogTime] < DATEADD(DAY, 1, CAST(CAST(@DateTime AS DATE) As DateTime) + CAST('00:07:00' As DateTime))

Of course, if you pass a Date variable instead of a DateTime, it will save you one conversion (you can use + to add datetime values together, but not date + time, so you still must convert to datetime):
SELECT *
FROM [LogEntries]
                -- 7 AM
WHERE [LogTime] >= CAST(@Date As DateTime) + CAST('00:07:00' As DateTime)
                -- 7 AM on the next day
AND  [LogTime] <= DATEADD(DAY, 1, CAST(@Date As DateTime) + CAST('00:07:00' As DateTime))


text:
Q: How to fetch endpoint of API with decorator function I'm implementing a login check (IAM is keycloak) with a decorator function on a Flask API.
There will be a separate endpoint ( /rt_group1/.../rt_group99/ ) for each user, let's say 100 in total.
I would like to prevent that I have to write 100 decorator functions.
Instead, I want to 'fetch' the endpoint inside the decorator function, and then compare in a database if the requesting user matches the appropriate endpoint.
the decorator:
def login_required(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        user_session = get_token()
        if  user_session......
            return f(*args, **kwargs)
        else:
            return 'Not logged in'
    return wrapper

routing:
@app.route("/rt_group1/", endpoint='route1')
@login_required
def render_dashboard():
    return redirect('/rt_group1/')

Any ideas how to get /rt_group1/ into the wrapper function?


text:
Q: How do I locate the offline file data in firefox I used to locate the file data by going to cache directory, which I would locate by typing about:cache  in the Firefox address bar. I can still navigate to this page but the file structure inside his has changed. Earlier I would take, say for example a file of maximum size and rename it to .flv to get it working as a video file. Now I am unable to locate this video files. does anybody have any idea as to where would you find the cached files in Firefox(say you watched a video in YouTube) and now you want it to access offline.
Thanks

A: Looks like this section of the developer documentation has the answer:

Storage location and clearing the offline cache
In Firefox, the offline cache data is stored separately from the Firefox profile—next to the regular disk cache:
Windows Vista/7: C:\Users\\AppData\Local\Mozilla\Firefox\Profiles\.\OfflineCache
Mac/Linux: /Users//Library/Caches/Firefox/Profiles/./OfflineCache

Source: https://developer.mozilla.org/En/Offline_resources_in_Firefox


text:
Q: Get podcasts on my IPhone through iTunes I've gone through the following steps:

*

*I loaded up iTunes 10 on a Windows7 machine

*I went to the iTunes store and subscribed to a podcast

*Library/podcasts has nothing in it, but there is a 1 in a circle by Podcasts Devices/my Iphone / Sync

*I checked my iPhone, but no podcasts are there

I really don't have a good times with the iTunes software. If someone could provide detailed step by step instructions of how to get podcasts onto my iPhone via iTunes I'd really appreciate it.
I know I can download podcasts direct to my iphone, but I would like to get it working through iTunes if I can.

A: If nothing has downloaded for the podcast you have suscribed to then there is probably nothing to download.
Have you tried other podcasts?
When you subscribe it should auto-download the lates podcast in that subscription.
As for transferring to the iPhone or an iPod, you have to make sure that Podcasts are turned on in the Sync section:


text:
Q: Why does creation of a Theano shared variable on GPU effect numpy's random streams? I'm just starting to play with Theano, and am wondering why the first creation of a shared variable on the gpu seems to effect numpy's random number generator. At times this initial creation seems to advance the random number generator.
I've explored the following test cases in this code:
import numpy

import theano
from theano.compile.sharedvalue import shared
import theano.sandbox.cuda as tcn

def make_cpu_shared():
    #Create, but don't return/use shared variable on cpu
    shared(theano._asarray(numpy.asarray([.67]), dtype='float32'), 'cpu_shared')
    return None

def make_gpu_shared():
    #Create, but don't return/use shared variable on gpu
    tcn.shared_constructor(theano._asarray(numpy.asarray([.67]), dtype='float32'), 'gpu_shared')
    return None

def rand_test0():
    #Match - Sanity check - Ensure numpy.random.seed creates repeatable random streams
    numpy.random.seed(666) #Note: 666 seems to be seed used in Theano test suite
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

    numpy.random.seed(666)
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

def rand_test1():
    #Match - Show creation of shared variable on cpu has no effect on random streams
    numpy.random.seed(666)
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

    numpy.random.seed(666)
    make_cpu_shared()
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

def rand_test2():
    #No Match - Show creation of shared variable on gpu effects random streams
    numpy.random.seed(666)
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

    numpy.random.seed(666)
    make_gpu_shared()
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

def rand_test3():
    #Match - Show effect is only for initial creation of shared gpu variable
    make_gpu_shared()

    numpy.random.seed(666)
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

    numpy.random.seed(666)
    make_gpu_shared()
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

def rand_test4():
    #No Match - Show initial creation of shared gpu variable effecting random streams
    numpy.random.seed(666)
    make_gpu_shared()
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

    numpy.random.seed(666)
    make_gpu_shared()
    temp = numpy.random.rand(1)
    print "temp[0]=",temp[0]

*

*rand_test0 - A sanity check to show I can reset a random stream using numpy.random.seed

*rand_test1 - Show creation of shared variable on cpu does nothing unexpected

*rand_test2 - Show creation of shared variable on gpu does have an unexpected effect

*rand_test3 - Show it is only the initial creation of the shared variable on the gpu with an unexpected effect

*rand_test4 - A verification of rand_test3

The results I got were as follows:
(Test 0 - Sanity Check)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test0()
temp[0]= 0.700437121858
temp[0]= 0.700437121858
>>>

(Test 1 - Shared on CPU OK)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test1()
temp[0]= 0.700437121858
temp[0]= 0.700437121858
>>>

(Test 2 - Shared on GPU effects random stream)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test2()
temp[0]= 0.700437121858
Using gpu device 0: GeForce GTX 670MX
temp[0]= 0.859992279406
>>>

(Test 3 - Only initial creation of shared variable on GPU effects random stream)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test3()
Using gpu device 0: GeForce GTX 670MX
temp[0]= 0.700437121858
temp[0]= 0.700437121858
>>>

(Test 4 - Variation on Test 3)
me@Bedrock1:~/Projects/Theano/packageTests$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from test_rand_shared import *
>>> rand_test4()
Using gpu device 0: GeForce GTX 670MX
temp[0]= 0.859992279406
temp[0]= 0.700437121858
>>>

Does this make sense to anyone? Is it a Theano artifact? Is it a CUDA artifact, caused by my initial access to the GPU (i.e. the fact that I was playing with shared variables is only incidental to what I'm seeing). Or, am I misunderstanding something else?

A: Theano's documentation talks about the difficulties of seeding random variables and why they seed each graph instance with its own random number generator.

Sharing a random number generator between different {{{RandomOp}}}
  instances makes it difficult to producing the same stream regardless
  of other ops in graph, and to keep {{{RandomOps}}} isolated.
  Therefore, each {{{RandomOp}}} instance in a graph will have its very
  own random number generator. That random number generator is an input
  to the function. In typical usage, we will use the new features of
  function inputs ({{{value}}}, {{{update}}}) to pass and update the rng
  for each {{{RandomOp}}}. By passing RNGs as inputs, it is possible to
  use the normal methods of accessing function inputs to access each
  {{{RandomOp}}}'s rng. In this approach it there is no pre-existing
  mechanism to work with the combined random number state of an entire
  graph. So the proposal is to provide the missing functionality (the
  last three requirements) via auxiliary functions: {{{seed, getstate,
  setstate}}}.

They also provide examples on how to seed all the random number generators.

You can also seed all of the random variables allocated by a
  RandomStreams object by that object's seed method. This seed will be
  used to seed a temporary random number generator, that will in turn
  generate seeds for each of the random variables.

>>> srng.seed(902340)  # seeds rv_u and rv_n with different seeds each

Try seeding the random variable's using Theano's seed functionality instead of numpy's.


text:
Q: Ternary coefficient of an integer in the range 1-1000 recursively in C
I have to find the ternary coefficients for a given number.

For example, if the given number is 29, the desired output should be -1101.
Some more examples: 7 would give 1-11 and 10 would give 101.
I tried to solve the problem recursively using character arrays but I am new to C and hence, there is a runtime error that I cannot solve. The code is given here -
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *coefficient();

int main()
{
    int n;
    printf("Input a number between 1 and 1000: ");
    scanf("%d",&n);
    if(n<1 || n>1000){
        printf("Invalid Input. Please try again");
        scanf("%d",&n);
    }

    //Calculating the size of the char array
    int dummyN = n;
    int count = 1;
    while(dummyN>1){
        count++;
        dummyN/=3;
    }
    char c[count];

    printf("Coefficient sequence %s\n",coefficient(n,c));
    return 0;
}

char *coefficient(int n, char *c){
    if (n>1){
        int rem = n%3;
        n = n/3;
        char finrem;
        if(rem==2){
            rem = -1;
            n++;
        }
        else finrem = rem +'0';
        strcat(c, finrem);
        c=coefficient(n,c);
    }
    else if (n==1){
        char i = '1';
        strcat(c, i);
    }
    return c;
}


text:
Q: How do I merge when one commit includes the changes from another commit? I have a project that's using git. When I received the repo, it had some uncommitted changes. I committed those, and started making my own.
I received work from another developer, and that developer committed both their changes and the original uncommitted changes into a single commit.
Now I have two git repos in separate folders and I'd like to know how I can merge my changes into the developers changes with as few conflicts as possible.

A: Assuming you have your tip currently checked out, and it is master, one option would be to:
 1. Add a remote from your repository pointing to theirs.
 2. Fetch in his changesgit fetch hisRemote
 2. Then create a new branch with only the changes you made, that is branched off of where you committed the original changes.  git branch myChanges
 3. Reset the master branch back to the commit where you committed the original changed git checkout mastergit reset --hard <commitOriginalChangesAreIn>
 4. Then merge his branch with his changes and the original changes into that branch.git merge hisRemoteBranch
 5. Finally merge that branch tip into the branch with your changes.git merge myChanges


text:
Q: Passing 2D array of objects to another Activity I'm trying to pass array of (objects) unfortunately (as far as i know) serializable bundle will not work with custom objects.
I have class seat:
   public class seat{
    boolean state;
    int Seatb;
    }

And here is a code from the first activity:
seat [][] arrseat=new seat[20][20];
Intent intent = new Intent(this, MainActivity2.class);
intent.putExtra("data", arrseat);
startActivity(intent);

Second activity:
seat [][] obseat=new seat[20][20];
Intent intent = getIntent();
obseat=intent.?

I could not find a way to get the array from intent

A: Arrays are serializable, So you can use putSerializable.
to put value
Intent i = new Intent(this, AnotherClass.class);
Bundle b = new Bundle();
b.putSerializable("arr", seat);
i.putExtras(b);

to get value
seat[][] arrseat = (seat[][]) bundle.getSerializable("arr");

also it is a similar problem here


text:
Q: BOSH CLI Expected to find a map at path ... but found '[]interface {}' Very similar to another question, but there are slight differences. Tried the accepted answer and still no luck.
I get this error when I run the command:
bosh -d prometheus deploy -n pfg-prometheus-boshrelease/manifests/prometheus.yml -o replace_vars.yml

Expected to find a map at path '/instance_groups/name=prometheus2/jobs/name=prometheus2/properties/prometheus/scrape_configs/job_name=bosh/static_configs/targets?' but found '[]interface {}'

replace_vars.yml:
- type: replace
  path: /instance_groups/name=prometheus2/jobs/name=prometheus2/properties/prometheus/scrape_configs/job_name=bosh/static_configs/targets?/-
  value: 192.168.123.26:9190

Manifest section:
- name: prometheus2
    properties:
      prometheus:
        rule_files:
        - ...
        scrape_configs:
        - file_sd_configs:
          - files:
            - /var/vcap/store/bosh_exporter/bosh_target_groups.json
          job_name: prometheus
          relabel_configs:
          - action: keep
            ...
          - regex: (.*)
            ...
        - job_name: bosh
          scrape_interval: 2m
          scrape_timeout: 1m
          static_configs:
          - targets:
            - localhost:9190

What would the correct path be?
EDIT: I have looked through bosh cli ops files but cannot find an example like mine.

A: I also stumpled upon this several times and never found a solution for this use case. What I usually do as a workaround is to replace one step up.
For your example:
/tmp/replace-vars.yml:
- type: replace
  path: /instance_groups/name=prometheus2/jobs/name=prometheus2/properties/prometheus/scrape_configs/job_name=bosh/static_configs/0
  value:
    targets:
    - 192.168.123.26:9190
    - localhost:9190

/tmp/test-manifest.yml:
instance_groups:
- name: prometheus2
  jobs:
    - name: prometheus2
      properties:
        prometheus:
          rule_files:
          - abc
          scrape_configs:
          - file_sd_configs:
          - files:
            - /var/vcap/store/bosh_exporter/bosh_target_groups.json
          job_name: prometheus
          relabel_configs:
          - action: keep
          - regex: (.*)
          - job_name: bosh
          scrape_interval: 2m
          scrape_timeout: 1m
          static_configs:
          - targets:
            - localhost:9190

Interpolated by bosh int /tmp/test-manifest.yml -o /tmp/replace-vars.yml:
instance_groups:
- jobs:
  - name: prometheus2
      properties:
        prometheus:
          rule_files:
          - abc
          scrape_configs:
          - file_sd_configs:
          - files:
            - /var/vcap/store/bosh_exporter/bosh_target_groups.json
          job_name: prometheus
          relabel_configs:
          - action: keep
          - regex: (.*)
          - job_name: bosh
          scrape_interval: 2m
          scrape_timeout: 1m
          static_configs:
          - targets:
            - 192.168.123.26:9190
            - localhost:9190
  name: prometheus2


text:
Q: Free group over a quotient of sets Given a set $S$, let $F_S$ denote the free group on the set $S$ (not the free abelian group).  Let $T \subseteq S$ be a subset.  Consider the quotient set $S/T$.  Is it true that $F_{S/T} \simeq F_S/F_T$ ?

A: According to the comment, something similar is true:

Let $T\subseteq S$ and consider the set difference $S\setminus T$, moreover let $(F_T)$ denote the normal subgroup generated by $F_T$ within the free group $F_S$.
  Then,
  $$F_S / (F_T) \cong F_{S\setminus T} \ . $$

Proof. Consider the mapping $\varphi_0:S\to F_S$ which maps all $t\in T$ to the unit element $e$ (empty word), but fixes all $s\in S\setminus T$. Since $F_S$ is free group over $S$, any function $S\to G$ to a group extends uniquely to a group homomorphism on $F_S$. In particular $\varphi_0$ induces a homomorphism $\varphi:F_S\to F_S$.
Now, the image of $\varphi$ is easily seen to be $F_{S\setminus T}$ (as embedded in $F_S$), and the kernel of $\varphi$ is going to be $(F_T)$, the collection of words in which, after 'deleting' all letters $t\in T$, what remains is the unit.

A: The functor $F : \mathsf{Set} \to \mathsf{Grp}$ is left adjoint, therefore preserves all colimits. If $T \subseteq S$ is a subset, and $T$ is non-empty, say $t_0 \in T$, then usually $S/T$ means the coequalizer of the two maps $T \rightrightarrows S$, where the first one is the inclusion and the second one is constant with value some $t_0 \in T$. It follows that $F(S/T)$ is the coequalizer of the two homomorphisms $F(T) \rightrightarrows F(S)$. Therefore, $F(S/T)=F(S)/N$, where $N$ is the normal subgroup generated by $\{t t_0^{-1} : t \in T\}$, or equivalently by $\{t t'^{-1} : t,t' \in T\}$.


text:
Q: Ruby on Rails: how to find the slowest tests? I'm writing tests using the default Rails testing framework. Is there a way to find which tests are the slowest?

A: How about minitest-reporters, as suggested here:
How can I generate a report that shows me my slowest running tests in Rails 3.2, Ruby 1.9?
It's Rails 4-compatible, and the Installation and Usage sections on GitHub show how to configure the SpecReporter option.


text:
Q: How can a run a login/logout script as root?
Possible Duplicate:
Where do I place a logout script for Lightdm?

How can I make login/logout scripts?
Something like /etc/gdm/PostSession/Default and /etc/gdm/PreSession/Default.


text:
Q: Why use macro when same job is done by a variable? in C language? I don't see the need of using macro to define something , say in below example:
#define TELEPHONE 443 //why use this

int telephone = 443; //when same job is done by a regular variable

why would any one use macro for defining (declaring variable in C language) ? as in above scenario?

A:
Why would any one use macro for defining (declaring variable in C language) ?

The macro does not define a variable, it defines a constant. Your C program that uses TELEPHONE that's #defined is indistinguishable to the compiler from a program that contains the hard-coded value 443.
Unlike int telephone variable, the TELEPHONE macro cannot be changed at run-time, and does not have an address.
Finally, it is possible to provide values for macros on the command line when calling the compiler - something impossible to do when you are dealing with C variables. Instead of defining #define TELEPHONE 443 you could pass the value on the command line, like this:
gcc -DTELEPHONE=443 myprog.c

A: Using a variable takes up space in the final image, which may not be required or desired (e.g. in embedded applications), whereas a define is handled strictly by the compiler (preprocessor).

A: There are several cases when a macro is more appropriate. The top of my head are:
1.To define a constant:
#define PI 3.1415926

2.To use as a constant expression.
#define BUFSIZE 1024

later you can use
int buffer[BUFSIZE];

This job cannot be done even if you use const int bufsize = 1024; (without using variable length array)

EDIT:
To clarify the use of const from the comment, in this code:
int main()
{
    const int x = 5;
    int array[x];
    return 0;
}

array is actually a variable length array, compile it with gcc test.c -std=c89  -pedantic, will generate the warning:
warning: ISO C90 forbids variable-size array `array'

The problem is, const variable in C isn't a constant expression, this is exactly my point of using #define in this situation. And this is one of the differences between C and C++.
Reference: C FAQ

A: dasblinkenlight pretty much covers it but I would just clarify some things they say, macros don't really define constants, you do that with the const modifier, and you should be using that most of the time. A macro defines substitution text, the only thing it knows about the language you are writing in is its use of spaces. So for macros you can do stuff like this
#define CODE_SNIPPET 10; i++ ) printf( "Hello %d\n"

for( int i = 0; i < CODE_SNIPPET , i );

which before being passed to the parser would be convert by the preprocessor to
for( int i = 0; i < 10; i++ ) printf( "Hello %d\n" , i );

Which is very powerful, but obviously open for abuse. I very rarely if ever use macros for constants, instead I will define the values as const in a .c file and then declare it extern in the header like
const int kAnswerToEveryThing = 42;    // .c file

extern const int kAnswerToEveryThing;        // .h file

I have one project that I use macros quite a bit, this is in Objective-C not c, but the macro system is identical and I have defined macros that expand out into class methods which add meta data to a class to be used by my library, its to do the same functionality as Java's annotations.


text:
Q: Computer names on network VB.Net I want to list all the connected network computers in a listbox. Does anyone know how?

A: Add a reference to System.DirectoryServices.
Add;
Imports System.DirectoryServices

Then use;
Private Delegate Sub UpdateDelegate(ByVal s As String)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim t As New Threading.Thread(AddressOf GetNetworkComputers)
    t.IsBackground = True
    t.Start()

End Sub

Private Sub AddListBoxItem(ByVal s As String)
    ListBox1.Items.Add(s)
End Sub

Private Sub GetNetworkComputers()
    Dim alWorkGroups As New ArrayList
    Dim de As New DirectoryEntry

    de.Path = "WinNT:"
    For Each d As DirectoryEntry In de.Children
        If d.SchemaClassName = "Domain" Then alWorkGroups.Add(d.Name)
        d.Dispose()
    Next

    For Each workgroup As String In alWorkGroups

        de.Path = "WinNT://" & workgroup
        For Each d As DirectoryEntry In de.Children

            If d.SchemaClassName = "Computer" Then

                Dim del As UpdateDelegate = AddressOf AddListBoxItem
                Me.Invoke(del, d.Name)

            End If

            d.Dispose()

        Next
    Next
End Sub

A: I chopped up some code to get you this, if its not perfect is should be close enough (hope it helps) ...
    Private Sub GetCurrentDevices()

    Try

        Dim ps As New System.Diagnostics.ProcessStartInfo("arp", "-a ")

        ps.RedirectStandardOutput = True
        ps.UseShellExecute = False
        ps.WindowStyle = ProcessWindowStyle.Hidden
        ps.CreateNoWindow = True

        Dim sbResults As New StringBuilder

        Using proc As New System.Diagnostics.Process()

            proc.StartInfo = ps
            proc.Start()

            Dim sr As System.IO.StreamReader = proc.StandardOutput

            While Not proc.HasExited
                System.Threading.Thread.Sleep(100)
            End While

            sbResults.Append(sr.ReadToEnd)

        End Using

        Dim IP_Address, MAC_Address, Device_Name As String

        Dim AllOutputLines() As String = sbResults.ToString.Split(vbCrLf)
        sbResults = Nothing

        For Each IndividualOutputLine As String In AllOutputLines

            Windows.Forms.Application.DoEvents()

            If IndividualOutputLine.Contains("dynamic") Then

                Dim Entries() As String = IndividualOutputLine.Split(New String() {}, StringSplitOptions.RemoveEmptyEntries)

                If Entries.Length = 3 Then

                   'Here is your info ...

                    IP_Address = Entries(0)
                    MAC_Address = Entries(1).ToUpper
                    Device_Name = GetComputerName(IP_Address)

                End If

            End If

        Next

          Catch ex As Exception

        MsgBox(ex.ToString)

    End Try

End Sub

Private Function GetComputerName(ByVal IP_Address As String) As String

    Dim ReturnValue As String = cUnknown

    Try

        Dim myIPs As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(IP_Address)
        ReturnValue = myIPs.HostName
        myIPs = Nothing

    Catch ex As Exception
    End Try

    If ReturnValue = IP_Address Then ReturnValue = cUnknown

    Return ReturnValue

End Function


text:
Q: How we can show different images for the mobile device and laptop device using image tag? Here my requirement is to be displaying one image for mobile devices and another image for the laptop devices, am trying with image tag but it was not working for me.
I want showing different images for mobile and laptop devices using the html
's image tag?

A: Well, it's not entirely what you need, because it doesn't check the type of device, but only the size of it... But in the RWD world it's enough, I guess.
You can use srcset. So instead of giving only one image, you put more of them and the browser does all the work selecting which one to show:
Here's some example:

And the logic behind that is pretty smart, because the browser tries to find the image that fits the best.
You can read more on that subject:

*

*https://css-tricks.com/responsive-images-youre-just-changing-resolutions-use-srcset/

*https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images

A: html :

css : `.img1
{display: block;}
.img2
{display: none;}
@media only screen and (max-width: 768px)
{
    .img1
    {
        display: none;
    }
    .img2
    {
        display: block;
    }
}   `


text:
Q: How to change the limit numbers of gerrit query when I was using gerrit query ssh -p 29418 exueniu@selngerrit.mo.sw.xxx.se gerrit query --start 10 status:merged 'project:wmr/wmr_xxx' it will only give me at most 500 results.

type: stats
  rowCount: 500
  runTimeMilliseconds: 196
  moreChanges: true

I have tried to use the parameter limit and set the limit to 700.
ssh -p 29418 exueniu@selngerrit.mo.sw.XXXX.se gerrit query --start 10 status:merged 'project:wmr/wmr_XXX' limit:700 it doesn't work, we still get only 500 results, anyone know how to get more results?

A: There's an internal 500 limit which is not explained very well in the Gerrit documentation:

If no limit is supplied an internal default limit is used to prevent
  explosion of the result set

To bypass this limit you need to have the Query Limit permission:

A: /changes/?o=CURRENT_REVISION&o=CURRENT_COMMIT&q=status:merged+after:2021-03-01+before:2021-03-25&start=0
/changes/?o=CURRENT_REVISION&o=CURRENT_COMMIT&q=status:merged+after:2021-03-01+before:2021-03-25&start=500
/changes/?o=CURRENT_REVISION&o=CURRENT_COMMIT&q=status:merged+after:2021-03-01+before:2021-03-25&start=1000

when the project changes over 500, param: n or limit does not work!
you can try this with param 'start', if start is null, the result limit is 500.
the /changes is query by pagenation.
when you receive the response,the last index of result have one param:_more_change;
when '_more_change' equals true,it means have next page. otherwise it reach to the end.
https://i.stack.imgur.com/z5xBE.png


text:
Q: Devexpress LookupEdit is not displaying the selected row for the last row I am using DevExpress.XtraEditors.LookUpEdit to display the information about the classes available. Currently it has 3 columns. The lookupedit is working perfectly except when I set the editValue to the last row. When the editvalue is set to any row other than the last one it shows the selected row when the lookupedit isn't opened yet when the lookupedit is set to the last row nothing is displayed. Currently I am :
lookupedit.Properties.ForceInitialize() ' Force it to initialize
lookupedit.Properties.PopulateColumns() ' Force the lookupedit to populate
   For i As Integer = 0 To tableData.Rows.Count - 1  ' Go through the information in it
      If lblClassVal.Text = tableData.Rows(i).Item(1).ToString() Then ' if the current row is equal to the value I want to select
          lookupedit.EditValue = i + 1 ' then I set the lookupedit value
      End If
   Next i
lookupedit.Properties.Columns("class_id").Visible = False  ' set two columns to invisible
lookupedit.Properties.Columns("active").Visible = False
lookupedit.Properties.Columns("class_name").Caption = "Class Name" ' set the 3rd column to a better title

Right now the lookupedit displays the selected text unless I select the last row, row number tableData.Rows.Count which then displays nothing. Yet when I print the values they are correct and when I remove the +1 when setting the lookupedit it sets it to the previous line I want an the first row can't be displayed.

A: Ok I solved this. Just in case someone else if having this problem I will leave the question up.
So the DevExpress LookUpEdit doesn't use the row number, it uses the ID column in your LookUpEdit table. So instead of selecting this by the row number set the EditValue to the ID number of the row you want to select. So instead of:
If lblClassVal.Text = tableData.Rows(i).Item(1).ToString() Then ' if the current row is equal to the value I want to select
   lookupedit.EditValue = i + 1 ' then I set the lookupedit value
End If

Use :
If lblClassVal.Text = tableData.Rows(i).Item(1).ToString() Then ' if the current row is equal to the value I want to select
   lookupedit.EditValue = tableData.Rows(i).Item(0).ToString() ' Where Item(0) is my ID number column
End If


text:
Q: How to add an 'id' property to the HTML 'ul' tag generated by the jQuery Autocomplete widget? I am using the jQuery Autocomplete widget and I would like to add an id property to the HTML ul tag generated by the mentioned widget. That is, I would like to change the code from

...

to

...

How can I make that in an easy and correct way?

A: Try this:
$("ul.ui-autocomplete").attr("id", "my_custom_id");
var id = $("ul.ui-autocomplete").attr("id");
alert(id);


text:
Q: How to give a file path in code instead of command line I've been working on my module exercises and I came across this code snippet which reads the text file and prints the details about it.
It's working fine, but I just want to know how to give the path of the text file in the code itself other than giving the path in the command line.
Below is my code.
class Module06
{
   public static void Exercise01(string[] args)
    {
        string fileName = args[0];
        FileStream stream = new FileStream(fileName, FileMode.Open);
        StreamReader reader = new StreamReader(stream);
        int size = (int)stream.Length;
        char[] contents = new char[size];
        for (int i = 0; i < size; i++)
        {
            contents[i] = (char)reader.Read();
        }
        reader.Close();
        Summarize(contents);
    }

    static void Summarize(char[] contents)
    {
        int vowels = 0, consonants = 0, lines = 0;
        foreach (char current in contents)
        {
            if (Char.IsLetter(current))
            {
                if ("AEIOUaeiou".IndexOf(current) != -1)
                {
                    vowels++;
                }
                else
                {
                    consonants++;
                }
            }
            else if (current == '\n')
            {
                lines++;
            }
        }
        Console.WriteLine("Total no of characters: {0}", contents.Length);
        Console.WriteLine("Total no of vowels    : {0}", vowels);
        Console.WriteLine("Total no of consonants: {0}", consonants);
        Console.WriteLine("Total no of lines     : {0}", lines);
    }
}

A: In your static void Main, call
string[] args = {"filename.txt"};
Module06.Exercise01(args);

A: Reading of a text file is much easier with File.ReadAllText then you don't need to think about closing the file you just use it. It accepts file name as parameter.
string fileContent = File.ReadAllText("path to my file");

A: string fileName = @"path\to\file.txt";


text:
Q: Python Flask Calling Functions Is it possible within the html template to call a python function? for example:
Call a function to check for a word within an input on the keypress event?
Thanks

A: You are able to call function in Flask, yes
for example:
def say_smt():
  print("hey")

@app.route('/')
def site():
  say_smt()

however using an input() would initiate a break in the whole script, so it would crash the whole Flask Server so that's not possible. Please be more specific about what your goal is


text:
Q: Azure CosmoDB has no option to set the scale mode even docs says so According to the docs:
https://learn.microsoft.com/de-de/azure/cosmos-db/how-to-provision-container-throughput?tabs=dotnetv2
https://github.com/MicrosoftDocs/azure-docs/blob/master/articles/cosmos-db/how-to-provision-autoscale-throughput.md#azure-cosmos-db-net-v3-sdk-for-sql-api
There should be an option to set the scale mode. Unfortunately, this is not the case which you can see in the screens.

So I'm wondering if they changed something and didn't update the docs or am I missing something?
I set the Capacity mode to Serverless.

A: This is expected behavior. The reason you're seeing this behavior is because you have configured your account to run in Serverless mode where there's no pre-configured throughput either at the database or container level. Throughput is adjusted automatically by Cosmos DB based on the usage.

but I can't change the capacity mode or can I?

Unfortunately no. It is not possible to switch between Serverless and Provisioned model as of today. You will have to create a new Cosmos DB account with Provisioned model.


text:
Q: Creating a startup folder shorcut with a ClickOnce application? I have created a ClickOnce application, available offline and can be reached through the start menu.
However, is it possible to set this application to launch on startup/set a shortcut in startup folder through code or settings rather than creating some sort of batch file to do it for me? ClickOnce options seem to be really limited!

A: You can found the answer to your question in here, Run ClickOnce app on startup
You can also use startup registry key to launch your application.
It is very simple to setup a key to launch a ClickOnce application and does not require setting up additional shortcuts. You simply use the shortcut created on install:
// The path to the key where Windows looks for startup applications
RegistryKey rk = Registry.CurrentUser.OpenSubKey(
                    @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);

//Path to launch shortcut
string startPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs)
                   + @"\YourPublisher\YourSuite\YourProduct";

rk.SetValue("YourProduct", startPath);


text:
Q: Do we have an Interface which provided all the styles in ios? I have a Style struct
Struct Style {
    var borderColor : UIColor

   init(borderColor : UIColor){
       self.borderColor = UIColor
   }
}

Anyone can now apply styling using Style object. But now I want to give users flexibility of passing any number of styling not just borderColor.
For example :
Struct Style {
    var borderColor : UIColor
    var someStyle : someStyleType
   init(borderColor : UIColor, someStyle: someStyleType, ...){
       self.borderColor = borderColor
       self.someStyle = someStyle
   }
}

If I will keep on typing different type of style there no of properties of Style is going to be very large. So what I was thinking, is to keep it dynamic in some way. Can somebody help me with some approach?
I want something like this, can we do this?
we can pass any number of parameters using the constructor, like
Struct Style: SomeInterfaceWhichProvideAllTheStyle {
   init(borderColor : UIColor, someStyle: someStyleType, anyNoOfArguments){
       super.borderColor = borderColor
       super.textColor = textColorStyle
   }
}


text:
Q: Android - is navigation drawer still a standard in new apps? Does a navigation drawer still considered as a standard when developing a new Android app? I see more and more apps without this drawer while Google apps still have it. If not, what is considered as standard for an Android app menu?

A: If you want a menu, then yes Navigation Drawer is still the standard.


text:
Q: Group by one column and calculate the median for the groups in matlab I read the following table from mysql into a matlab cell array:
Nyse = fetch(conn,'SELECT ticker,date,utcsec,bid,ofr FROM HFE.Quotes where ex="N" order by utcsec,bid;');

The Nyse cell array contain 1000000 rows. And I want to calculate the median bid for each second, where the second is recorded as a string in the utcsec column. I do it in the following way:
utcsec=cell2mat(Nyse(:,3));
bid=cell2mat(Nyse(:,4));
NyseBid=grpstats(bid,utcsec,{'median'});

The problem is that the function grpstats takes around 70 sec to do the task. The question is, how can I optimize the code so it will run faster?
An example string in the UTCSEC column is '09:30:00'.

A: I suggest you checkout this question and these answers as it is a highly related problem.
To apply the results of that thread to this problem, I would use this MEX function I wrote which takes in an array of groupIDs and extracts which rows each group is on. This allows efficient aggregation by group.
As I understand, utcsec is essentially a groupID and bid is the array to aggregate. The code would go:
utcsec = Nyse(:,3);    %utcsec in this should be a cell array o fstrings
[unique_utcsec, map] = mg_getRowsWithKey(utcsec);  %call to my magic function
         %unique_utcsec contains unique strings in utcsec
         %map shows us which rows correspond to each unique second

median_bid = zeros(length(unique_utcsec), size(bid,2));

for i = 1:length(unique_utcsec)  %iterate over each utc second
    median_bid(i,:) = median(bid(map{i},:),1);  %calculate the median for that second
end

In my testing, this code is significantly faster than Matlab's implementation with the grpstats function. There are alternative approaches in that thread as well that do not rely on mex. The mex c++ code should be compiled with:
mex -largeArrayDims mg_getRowsWithKey.cpp

And then the function mg_getRowsWithKey can be called like any Matlab function. mg_getRowsWithKey is written in c++ using STL libraries such as map.


text:
Q: Environment specific database connection configurations in Drupal 8 Settings.php I am trying to pass environment variables to settings.php file for database configurations in Drupal, I am able to access the environment variables and store them to variables and pass those variables to database array in settings.php
If i print the array to console it prints fine, but while accessing the website Apache log gives below error
I have tried directly passing env variable using getenv()
Passing the env variable to another variable and passing that new variable to database array
Converting the Variable to UTF-8 encoding and passing it to database array
If I hardcode the database configuration values it works fine, but when I try to read it through env variable it does not work! I am not able to understand why is not working when the values passes seem to be ok
Error Log Stack
Drupal\\Core\\Database\\DatabaseAccessDeniedException: SQLSTATE[HY000] [1045] Access denied for user ''@'localhost' (using password: NO) in /var/www/html/core/lib/Drupal/Core/Database/Driver/mysql/Connection.php on line 427

Code in Settings.php
$vars = array(
  'DB_HOST',
  'DB_USERNAME',
  'DB_PASSWORD',
  'DB_PORT'
);
foreach($vars as $var) {
  if(!isset($_ENV[$var]) && getenv($var)){
    $_ENV[$var] = getenv($var);
  }
}

$username = mb_convert_encoding($_ENV['DB_USERNAME'], "UTF-8");
$password = mb_convert_encoding($_ENV['DB_PASSWORD'], "UTF-8");
$host = mb_convert_encoding($_ENV['DB_HOST'], "UTF-8");
$port = mb_convert_encoding($_ENV['DB_PORT'], "UTF-8");

$databases['default']['default'] = array (
  'database' => 'a_16a7f4a6-74a2-4066-aaa6-c0f4029f9a9f',
  'username' => $username,
  'password' => $password,
  'prefix' => '',
  'host' => $host,
  'port' => $port,
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);
print_r($databases);

Output when I just run the php file it displays
Array
(
  [default] => Array
    (
        [default] => Array
            (
                [database] => a_16a7f4a6-74a2-4066-aaa6-c0f4029f9a9f
                [username] => root
                [password] => root
                [prefix] =>
                [host] => localhost
                [port] => 3306
                [namespace] => Drupal\Core\Database\Driver\mysql
                [driver] => mysql
            )

    )

)


text:
Q: need assistance Ultragrid (infragistics). cant combine data columns from 2 sources i have a project with winform and VB.net.
i got there 2 UltraGrids (infragistics) that each one has its own data source.
its working great but i need to do some changes.
how can i combine a field to the first from the other?
i have tried to change columns with the Ultragrid designer, even though i can see it, it doesn't show.
the first grid gets datasource and the other gets the data from SQL Query.
is it only by code or there is a shortcut?


text:
Q: Bash strings getting cut off when outputting from array at space marks So I am going through a log file and extracting information from said log file such as device name, location, and time of log. It looks something like the following:
edge2.mco1-9 Jun 11:32:24 GMT %SEC_LOGIN-5-LOGIN_SUCCESS: Login Success

I am coming across an issue where when I run the following:

for y in ${DeviceName[@]}
do
    echo "Device: $y"
    counter=1
    for z in ${LocationName[@]}
    do
        testing=($(grep "$y\.$z\-.*\%" hacker.txt | cut -f2 -d "-" | cut -f1 -d% | head -n 1))
        if [[ ${testing[$counter]} =~ [^0-9] ]]
        then
            echo $z
            echo $testing
        fi

    done

done

the day number is the only part outputted. DeviceName is an array of device names. LocationName is an array of location names. The complicated part was due to me wanting to only output the location name if it had something coming from the grep since I did not want a long list of locations that had no time attached to it. I did experiment with saving to a .txt file, which did do the correct time, but it seems outputting the correct time is more troublesome due to spaces. Using the example,
9 Jun 11:32:24 GMT

should be the output. Is there any way to get around this?
The $testing is kept as attempts to do ${testing[$counter]}, $(${testing[$counter]}), and other methods did not work giving me errors. Errors are Jun and ./finder: line 113: Jun: command not found respectively $testing at least gives me the day number. Obviously there is an issue with spaces but I don't know how to fix this.

A: Setup:
$ cat hacker.txt
edge2.mco1-9 Jun 11:32:24 GMT %SEC_LOGIN-5-LOGIN_SUCCESS: Login Success
$ y=edge2
$ z=mco1

The grep command:
$ grep "$y\.$z\-.*\%" hacker.txt | cut -f2 -d "-" | cut -f1 -d% | head -n 1
9 Jun 11:32:24 GMT

Loading this into the testing[] array:
$ testing=( $(grep "$y\.$z\-.*\%" hacker.txt | cut -f2 -d "-" | cut -f1 -d% | head -n 1) )
$ typeset -p testing
declare -a testing=([0]="9" [1]="Jun" [2]="11:32:24" [3]="GMT")

Running the test:
$ counter=1
$ [[ ${testing[$counter]} =~ [^0-9] ]] && echo "success"
success

# turn on debugging to see what we're testing:
$ set -xv                                                  # turn on debugging

$ [[ ${testing[$counter]} =~ [^0-9] ]] && echo "success"
[[ ${testing[$counter]} =~ [^0-9] ]] && echo "success"
+ [[ Jun =~ [^0-9] ]]                                      # contents of testing[1] == 'Jun'
+ echo success
success

$ set +xv                                                  # turn off debugging

So far so good.
OP has stated the desired output should look like:
9 Jun 11:32:24 GMT

But the current echo command has an issue:
echo $testing

$testing is an array; without an index bash treats $testing the same as ${testing[0]} which in this case outputs 9 (see the output from typeset -p testing - above); to output the entire contents of the array OP can use:
$ echo "${testing[@]}"
9 Jun 11:32:24 GMT

Net result: OP should be able to change echo $testing to echo "${testing[@]}" to obtain the desired output.

OP has mentioned the code complication (loading testing[] array, comparing testing[1] ???) is due to only printing output if grep finds a match.
We can streamline the code a bit by replacing the guts of the for z loop with:
    # no need for array, just capture datetime stamp:

    dtstamp=$(grep "$y\.$z\-.*\%" hacker.txt | cut -f2 -d "-" | cut -f1 -d% | head -n 1)

    # is length of 'dtstamp' non-zero?

    if [[ -n "${dtstamp}" ]]
    then
        echo "${z}"
        echo "${dtstamp}"
    fi

If the objective is to only print ${z} when grep finds a match (ie, OP doesn't need to print ${dtstamp}) we can streamline the code a bit more to where the only command in the for z loop is:
grep "$y\.$z\-.*\%" hacker.txt >/dev/null && echo "${z}"

Demo:
$ z=mco1
$ grep "$y\.$z\-.*\%" hacker.txt >/dev/null && echo "${z}"
mco1

$ z=xxxx
$ grep "$y\.$z\-.*\%" hacker.txt >/dev/null && echo "${z}"
              <<<=== no output

NOTES:

*

*can also remove the counter=1 from the current code

*OP should consider cutting-n-pasting their code (along with the appropriate shebang, eg, #!/bin/bash) into shellcheck.net; this will report on syntax issues as well as make some suggestions re: 'best practices'


text:
Q: How to deploy my first javascript web app onto the web for actual use I built my first javascript app using HTML and CSS as well.  It is a basic tip calculator.  I've pushed my code to my GIT but when i click on website deployed its just the README file.  I have a feeling I need to use Node.js but after the basic reading I did on it I have no idea how to accomplish this. I just want to push the app to heroku or even just off the GIT page to see it in action on another device.
I tried running npm init and it created a package.JSON but every time i pushed to heroku the app would crash and give me an error stating it can not find the "start" script i input.
here's my github for the app, https://github.com/jaronow/tip-calculator. I would appreciate some basic guidance or a link to somewhere i can learn how to accomplish this task

A: You don't need to use Heroku for a one page web app like yours. You can host it directly on Github using GitHub Pages. You want to choose the "Project Site" instructions. Pay attention to selecting the "source" when you go through the steps. You'll want to specify your html/main.html file.
Also, looking at your code, you should consider renaming your "java" folder either "js" or "javascript" or something similar. Java is a different language and naming it that is confusing.
You do not need to use NodeJS for this project because there is nothing that runs on the server side. Everything runs in the browser: the HTML, CSS, and JavaScript.

A: In order to deploy to heroku , you would have to use Node and you will have to set up a basic server to serve your static assets such as the HTML , Images, and CSS.
To deploy or host your app you can use Github pages, I am not sure if you have ever heard of it.
Here is this link: https://pages.github.com/
on the page it should have a step-by-step guide on how to host it.


text:
Q: Could not resolve view with name 'forward:/oauth/confirm_access' error in Spring OAuth2 I'm getting the following error in Spring OAuth2:
javax.servlet.ServletException: Could not resolve view with name 'forward:/oauth/confirm_access' in servlet with name 'dispatcherServlet'
    at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1237) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1037) ~[spring-webmvc-4.3.2.RELEASE.jar:4.3.2.RELEASE]

By debugging in Spring impelmentation I noticed that it is hardcoded this view name. Shouldn't it be implemented in Spring? I suppose I shall not build that view and is just a matter of configuration.
My OAuth2 authorization server and resource servers are properly configured, so I skiped that part.
Is there a configuration that handles this view?
Thanks.
P.S I am using Postman client to generate token.

A: I just found the problem.
The client should have autoApprove flag set on true.


text:
Q: Received fatal alert: handshake_failure error in JSP page I have a strange problem with authorized ssl connection. First I have created java class that connects to external server with authorized ssl. I've run this class in command line it works fine, gets desired results from external server. After I've use this class in JSP page. After reboot my tomcat JSP page gets me desired results, too. But after 10-15 requests JSP page gives me this error: "javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure ". No more desired results in JSP page.
Here is method in java class code:
public String TransHttpsAuth(String server, String param, String method, String jksPath, String jksPass)
{
    try
    {
        System.setProperty("javax.net.ssl.keyStoreType", "jks");
        System.setProperty("javax.net.ssl.keyStore", jksPath);
        System.setProperty("javax.net.ssl.keyStorePassword", jksPass);

        server=server+"/?"+ param;

        URL url = new URL(server);
        HttpsURLConnection httpurlconnection = (HttpsURLConnection)url.openConnection();

        httpurlconnection.setHostnameVerifier(new NullHostnameVerifier());
        httpurlconnection.setRequestMethod(method);
        httpurlconnection.setDoOutput(true);

        httpurlconnection.connect();
       InputStreamReader in = new InputStreamReader((InputStream) httpurlconnection.getContent());

       BufferedReader buff = new BufferedReader(in);
       String line = buff.readLine();
        StringBuffer text = new StringBuffer();
       while (line != null) {
           text.append(line + "\n");
           line = buff.readLine();
       }
       System.out.println(text.toString());
       httpurlconnection.disconnect();
        return text.toString();
    }
    catch(Exception exception)
    {
        return exception+"";
    }
}

Calling from JSP page: <%
 fsb fsb = new fsb();
out.println(fsb.TransHttpsAuth("https://ext_server","prameters","GET", "jks_path", "password"));
%>
Tomcat version: 6.0.32
Java version: 1.6.0_21

A: You will need to add the server certificate in your jre and restart tomcat in order to connect using java. Look for InstallCert.java on the web.