text:
Q: how to inject script into document  without jquery I am building a browser extension and I have a function inside of <script> tags that modifies the DOM that I need to inject into the <head> of any given webpage. The entire function is a string("<script>function content blah blah</script>"). I was using jquery to achieve this:
$('head').prepend(modFunction);

and this works fine. I would like to remove jQuery for a few reasons but when I try to create a <script> element to inject into the <head> with vanilla javascript everything fails. I have tried two methods so far:
1.
  var headSelector = document.querySelector('head');
  var el = document.createElement('div');
  el.innerHTML = modFunction;
  modFunction = el.firstChild;
  headSelector.insertBefore(modFunction, headSelector.firstChild);

2.document.head.insertAdjacentHTML('afterbegin', modFunction);
Both javascript attempts inject a <script> tag with the correct function into the <head>, however, neither executes the function. Not sure why jQuery is working and the vanilla javascript doesn't. Any help would be greatly appreciated. Thanks

A: You have a few mistakes.

*

*If your modFunction is a string that contains <script> tag before and after it, your code won't work, because changing innerHTML of div will not execute added scripts.

*Using insertAdjacentHTML function is unneccesary, because modFunction is now object of type Text, which will insert [object Text] string before your script.

*Instead, use appendChild function to insert properly new script element into head.
Although @Jantho1990 said that it is better to load script from file instead, many browsers use cache, so if you change your script source, it wont be always visible in browsers.
var scriptSource = '//YourScriptSource.....';
var scriptElem = document.createElement('script');
scriptElem.text = scriptSource;
document.head.appendChild(scriptElem);

A: SoftwareEngineer171's answer works (see text in https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script), but I would like to point out a couple of things:

*

*You shouldn't be injecting <div> elements into the <head>. It's invalid HTML and a bad practice in general.

*Generally, it is preferable to store your JavaScript on your server as a file and use the src attribute to get that file onto the page. Not only is that more secure, it also saves you a lot of work when you need to go back and update the code.
I would recommend the following solution:
yourJavaScriptFile.js
    function content blah blah

Inline:
    <script type="text/javascript" src="yourJavaScriptFile.js"></script>


text:
Q: How to limit a Type type to a specific types subset in C# A variable of type Type can contain any type. What I need is a variable that can only contain types that inherit a specific class and implement a specific interface. How can this be specified? I have tried declaring the variable as
Type: MyClass, IMyInterface theTypeVariable;

and as
Type<MyClass, IMyInterface> theTypeVariable;

but neither works.
what's the correct way?
For example
class A {...}

class B {...}

interface IC {...}

interface ID {...}

class E: B, IC {...}

class F: B, IC, ID {...}

class G: ID {...}

...

// This following line invalid actually,
// so it is pseudocode of a kind
// the syntactically and semantically correct form of this is the question
Type: B, IC theTypeVariable; // or Type<B, IC> theTypeVariable // perhaps

theTypeVariable = typeof(E); // This assignment is to be valid.

theTypeVariable = typeof(F); // This assignment is to be valid.

theTypeVariable = typeof(A); // This assignment is to be invalid.

theTypeVariable = typeof(B); // This assignment is to be invalid.

theTypeVariable = typeof(IC); // This assignment is to be invalid.

theTypeVariable = typeof(G); // This assignment is to be invalid.

For a more definite example: I may want to declare a type variable that can only contain any types that extend List<T> and implement IDisposable (a disposable list of Ts, not a list of disposables).
E.g. I will implement DisposableList<T>: List<T>, IDisposable and AnotherDisposableListImplementation<T>: List<T>, IDisposable classes and I want a variable that will be able to store typeof(DisposableList<Foo>) and typeof(AnotherDisposableListImplementation<Foo>) but not typeof(Foo) nor typeof(List<Foo>).

A: I believe this is what you are looking for
 public class EstentedList<Type> where Type:List<T>,IDisposable
 {

 }

you can use this class as Type for your variables

A: Type contains metadata about a type; it is part of the reflection API. This is not valid:
Type x = 5;
Type y = "Hello Sailor!";

To have a type U which is a subtype of T and implements interface I you can use generics:
... Foo<U>(...)
where U : T, I
{
  U myvar;
}

You can create a new type in this way:
class MyType : MyClass, IMyInterface
{
  private MyClass A;
  private IMyInterface B;

  private MyType(MyClass a, IMyInterface b)
  {
    A = a;
    B = b;
  }

  public static MyType Create<U>(U x)
  where U : MyClass, IMyInterface
  {
    return new MyType(x, x);
  }

  // Implementations of MyClass and IMyInterface
  // which delegate to A and B.

}

Now variables with type MyType are a subtype of MyClass and IMyInterface.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iOS: how to remove xib files caching? My application is localized in two languages. I have pairs of xib files for the two localizations. When I change the device/simulator language, or when I modify xib files and rebuild-run the application, the old xib files are still used in the application, seem to be cached somewhere. How to tell my app to delete cached xib files?
Edit:
Check this scene:
On device, I run the app while the device language is English, all xib files are English. Then I change device language to Arabic, restart the device, Xib files still english!
what is the problem? and how to solve it?

A: From Xcode:

*

*Build Menu -> Clean

and/or

*

*Delete app from simulator

(usually I do both)
Make sure the xib are only in the localized directories


text:
Q: Parsing json object and array with same model from api call using retrofit i am calling a api in android using retrofit and trying to get json object as a response and map that json object onto my model object but i am getting this error

java.lang.IllegalStateException: Expected BEGIN_ARRAY but was
  BEGIN_OBJECT at line 12 column 22 path $.data[0].salary

i cant change anything in the server response because i am dealing with only front end, so if there is anything wrong even with the server response please let me know how can i handle that thing on my end
Server Response
{
"header": "200",
"status": "success",
"data": [
    {
      "id": 1,
      "job_title": "Software Engineer",
      "city": "Yogyakarta",
      "country": "Indonesia",
      "logo": "https://s3-ap-southeast-1.amazonaws.com/ricebowl/employers/4913.png",
      "company_name": "A Job Thing",
      "salary": {
            "currency": "IDR",
            "minimum": "5000000",
            "maximum": "10000000"
      },
      "created_at": "2018-10-01T00:30:00+0000",
      "job_type": "Full Time",
      "share_url":"https://ajobthing.com/",
      "description": "A Job Thing is a recruitment platform tools for hiring better staff. AJobThing helping facilitate the recruitment process of talented candidates for the organization. We attract the best candidates allowing us the opportunity to source and select the best talents to match company requirements.\n\nIn March 2018, A Job Thing became the best Job Portal and Win Asia Recruitment Awards 2018 held by HR Asia Recruitment. We are committed to continuously improving the value we provide as best HR tools to help hiring talented candidates. To deliver on this, we continue to evolve our platform and service offerings to be the best recruiting tools.",
      "responsibility": "

Advocating automated testing and code quality

Constantly monitoring, and improving the performance for all backend stacks

Responding to alerts, pings, pages and queries

Thinking ahead to sustain reliability and availability by building instrumentation and profiling tools, accommodating our rapidly growing user base

Following new technologies, being eager to adapt them

Implementing automated services, for repetitive day-to-day tasks

Answering daily questions from users, collaborating with Support Engineers to investigate and solve support issues

",
      "requirement": "

Knowledge of A Job Thing and passion for the product

Strong computer science fundamentals, including data structures, algorithms and programming languages

Strong knowledge of cloud architecture and application deployment

Understanding of basic security concepts (e.g. Symmetric and Asymmetric encryption, Secure Key Exchange)

Clear and positive communication skills in written and spoken English

"
    },
    {
      "id": 2,
      "job_title": "Software Engineer",
      "city": "Istanbul",
      "country": "Turkey",
      "logo": "https://zeplin.io/img/favicon/256x256.png",
      "company_name": "Zeplin",
      "salary": {
            "currency": "USD",
            "minimum": "5000",
            "maximum": "10000"
      },
      "created_at": "2018-10-02T23:18:00+0000",
      "job_type": "Internship",
      "share_url":"https://ajobthing.com/",
      "description": "Zeplin is a connected space for product teams where they can share designs, generate specs, assets and code snippets. In just 2 years, we've reached over 1,500,000 users from the best product teams like Airbnb, Dropbox, Pinterest, Microsoft and many many more. We're a Y Combinator startup, also backed by amazing investors like Elad Gil, Mike Maples, Kevin Hale. We're a small, distributed crew with offices in San Francisco and Istanbul.",
      "responsibility": "

Advocating automated testing and code quality

Constantly monitoring, and improving the performance for all backend stacks

Responding to alerts, pings, pages and queries

Thinking ahead to sustain reliability and availability by building instrumentation and profiling tools, accommodating our rapidly growing user base

Following new technologies, being eager to adapt them

Implementing automated services, for repetitive day-to-day tasks

Answering daily questions from users, collaborating with Support Engineers to investigate and solve support issues

",
      "requirement": "

Knowledge of A Job Thing and passion for the product

Strong computer science fundamentals, including data structures, algorithms and programming languages

Strong knowledge of cloud architecture and application deployment

Understanding of basic security concepts (e.g. Symmetric and Asymmetric encryption, Secure Key Exchange)

Clear and positive communication skills in written and spoken English

"
    },
    {
      "id": 3,
      "job_title": "Software Engineer",
      "city": "Singapore",
      "country": "Singapore",
      "logo": "https://grab.careers/wp-content/themes/grabcareer/images/Grab_logo.png",
      "company_name": "Grab",
      "salary": {
            "currency": "SGD",
            "minimum": "5000",
            "maximum": "10000"
      },
      "created_at": "2018-10-10T00:30:00+0000",
      "job_type": "Full Time",
      "share_url":"https://ajobthing.com/",
      "description": "Grab is more than just the leading ride-hailing app in Southeast Asia. We use data and technology to improve everything from transportation to payments and logistics across Southeast Asia.\n\nWorking with governments, drivers, passengers and charities, we aim to unlock the true potential of the region by solving the problems that hinder progress. If you share our vision of Driving Southeast Asia Forward, apply to join our team today.",
      "responsibility": "

Advocating automated testing and code quality

Constantly monitoring, and improving the performance for all backend stacks

Responding to alerts, pings, pages and queries

Thinking ahead to sustain reliability and availability by building instrumentation and profiling tools, accommodating our rapidly growing user base

Following new technologies, being eager to adapt them

Implementing automated services, for repetitive day-to-day tasks

Answering daily questions from users, collaborating with Support Engineers to investigate and solve support issues

",
      "requirement": "

Knowledge of A Job Thing and passion for the product

Strong computer science fundamentals, including data structures, algorithms and programming languages

Strong knowledge of cloud architecture and application deployment

Understanding of basic security concepts (e.g. Symmetric and Asymmetric encryption, Secure Key Exchange)

Clear and positive communication skills in written and spoken English

"
    },
    {
      "id": 4,
      "job_title": "Software Engineer",
      "city": "Jakarta",
      "country": "Indonesia",
      "logo": "https://teatoxnco.com/store/wp-content/uploads/2017/08/logo-tokopedia.png",
      "company_name": "Tokopedia",
      "salary": {
            "currency": "IDR",
            "minimum": "5000000",
            "maximum": "10000000"
      },
      "created_at": "2018-10-11T23:18:00+0000",
      "job_type": "Internship",
      "share_url":"https://ajobthing.com/",
      "description": "Tokopedia is an Indonesian technology company with a mission to democratize commerce through technology. We are the leading marketplace in Indonesia; we encourage millions of merchants and consumers to participate in the future of commerce. Our vision is to build an ecosystem where everyone can start and discover anything with ease",
      "responsibility": "

Advocating automated testing and code quality

Constantly monitoring, and improving the performance for all backend stacks

Responding to alerts, pings, pages and queries

Thinking ahead to sustain reliability and availability by building instrumentation and profiling tools, accommodating our rapidly growing user base

Following new technologies, being eager to adapt them

Implementing automated services, for repetitive day-to-day tasks

Answering daily questions from users, collaborating with Support Engineers to investigate and solve support issues

",
      "requirement": "

Knowledge of A Job Thing and passion for the product

Strong computer science fundamentals, including data structures, algorithms and programming languages

Strong knowledge of cloud architecture and application deployment

Understanding of basic security concepts (e.g. Symmetric and Asymmetric encryption, Secure Key Exchange)

Clear and positive communication skills in written and spoken English

"
    },
    {
      "id": 5,
      "job_title": "Software Engineer",
      "city": "Remote",
      "logo": "https://images-na.ssl-images-amazon.com/images/I/51rttY7a%2B9L._SY355_.png",
      "company_name": "Spotify",
      "salary": {
            "currency": "EUR",
            "minimum": "5000",
            "maximum": "10000"
      },
      "created_at": "2018-10-12T00:30:00+0000",
      "job_type": "Full Time",
      "share_url":"https://ajobthing.com/",
      "description": "With Spotify, it's easy to find the right music for every moment – on your phone, your computer, your tablet and more.\n\nThere are millions of tracks on Spotify. So whether you're working out, partying or relaxing, the right music is always at your fingertips. Choose what you want to listen to, or let Spotify surprise you.\n\nYou can also browse through the music collections of friends, artists and celebrities, or create a radio station and just sit back.",
      "responsibility": "

Advocating automated testing and code quality

Constantly monitoring, and improving the performance for all backend stacks

Responding to alerts, pings, pages and queries

Thinking ahead to sustain reliability and availability by building instrumentation and profiling tools, accommodating our rapidly growing user base

Following new technologies, being eager to adapt them

Implementing automated services, for repetitive day-to-day tasks

Answering daily questions from users, collaborating with Support Engineers to investigate and solve support issues

",
      "requirement": "

Knowledge of A Job Thing and passion for the product

Strong computer science fundamentals, including data structures, algorithms and programming languages

Strong knowledge of cloud architecture and application deployment

Understanding of basic security concepts (e.g. Symmetric and Asymmetric encryption, Secure Key Exchange)

Clear and positive communication skills in written and spoken English

"
    },
    {
      "id": 6,
      "job_title": "Software Engineer",
      "city": "Remote",
      "logo": "https://pmcdeadline2.files.wordpress.com/2018/08/airbnb-logo.jpg?w=446&h=299&crop=1",
      "company_name": "Airbnb",
      "salary": [],
      "created_at": "2018-10-22T23:18:00+0000",
      "job_type": "Full Time",
      "share_url":"https://ajobthing.com/",
      "description": "Founded in 2008, Airbnb's mission is to create a world where people can belong through healthy travel that is local, authentic, diverse, inclusive and sustainable. Airbnb uniquely leverages technology to economically empower millions of people around the world to unlock and monetize their spaces, passions and talents to become hospitality entrepreneurs. Airbnb's accommodation marketplace provides access to 5+ million unique places to stay in more than 81,000 cities and 191 countries. With Experiences, Airbnb offers unprecedented access to local communities and interests through 15,000+ unique, handcrafted activities run by hosts across 1,000+ markets around the world. Airbnb's people-to-people platform benefits all its stakeholders, including hosts, guests, employees and the communities in which it operates.",
      "responsibility": "

Advocating automated testing and code quality

Constantly monitoring, and improving the performance for all backend stacks

Responding to alerts, pings, pages and queries

Thinking ahead to sustain reliability and availability by building instrumentation and profiling tools, accommodating our rapidly growing user base

Following new technologies, being eager to adapt them

Implementing automated services, for repetitive day-to-day tasks

Answering daily questions from users, collaborating with Support Engineers to investigate and solve support issues

",
      "requirement": "

Knowledge of A Job Thing and passion for the product

Strong computer science fundamentals, including data structures, algorithms and programming languages

Strong knowledge of cloud architecture and application deployment

Understanding of basic security concepts (e.g. Symmetric and Asymmetric encryption, Secure Key Exchange)

Clear and positive communication skills in written and spoken English

"
    }]}

My object model
 package com.example.jobportal.models;

    import java.util.List;
    import com.google.gson.annotations.SerializedName;

    public class JobRecommendationsResponse{

        @SerializedName("data")
        private List<DataItem> data;

        @SerializedName("header")
        private String header;

        @SerializedName("status")
        private String status;

        public void setData(List<DataItem> data){
            this.data = data;
        }

        public List<DataItem> getData(){
            return data;
        }

        public void setHeader(String header){
            this.header = header;
        }

        public String getHeader(){
            return header;
        }

        public void setStatus(String status){
            this.status = status;
        }

        public String getStatus(){
            return status;
        }

        @Override
        public String toString(){
            return
                "JobRecommendationsResponse{" +
                "data = '" + data + '\'' +
                ",header = '" + header + '\'' +
                ",status = '" + status + '\'' +
                "}";
            }
    }

    package com.example.jobportal.models;

    import com.google.gson.annotations.SerializedName;

    public class Salary{

        @SerializedName("maximum")
        private String maximum;

        @SerializedName("currency")
        private String currency;

        @SerializedName("minimum")
        private String minimum;

        public void setMaximum(String maximum){
            this.maximum = maximum;
        }

        public String getMaximum(){
            return maximum;
        }

        public void setCurrency(String currency){
            this.currency = currency;
        }

        public String getCurrency(){
            return currency;
        }

        public void setMinimum(String minimum){
            this.minimum = minimum;
        }

        public String getMinimum(){
            return minimum;
        }

        @Override
        public String toString(){
            return
                "Salary{" +
                "maximum = '" + maximum + '\'' +
                ",currency = '" + currency + '\'' +
                ",minimum = '" + minimum + '\'' +
                "}";
            }
    }

    package com.example.jobportal.models;

    import com.google.gson.annotations.SerializedName;

    public class DataItem{

        @SerializedName("job_type")
        private String jobType;

        @SerializedName("country")
        private String country;

        @SerializedName("city")
        private String city;

        @SerializedName("created_at")
        private String createdAt;

        @SerializedName("description")
        private String description;

        @SerializedName("requirement")
        private String requirement;

        @SerializedName("salary")
        private Salary salary;

        @SerializedName("responsibility")
        private String responsibility;

        @SerializedName("share_url")
        private String shareUrl;

        @SerializedName("company_name")
        private String companyName;

        @SerializedName("logo")
        private String logo;

        @SerializedName("id")
        private int id;

        @SerializedName("job_title")
        private String jobTitle;

        public void setJobType(String jobType){
            this.jobType = jobType;
        }

        public String getJobType(){
            return jobType;
        }

        public void setCountry(String country){
            this.country = country;
        }

        public String getCountry(){
            return country;
        }

        public void setCity(String city){
            this.city = city;
        }

        public String getCity(){
            return city;
        }

        public void setCreatedAt(String createdAt){
            this.createdAt = createdAt;
        }

        public String getCreatedAt(){
            return createdAt;
        }

        public void setDescription(String description){
            this.description = description;
        }

        public String getDescription(){
            return description;
        }

        public void setRequirement(String requirement){
            this.requirement = requirement;
        }

        public String getRequirement(){
            return requirement;
        }

        public void setSalary(Salary salary){
            this.salary = salary;
        }

        public Salary getSalary(){
            return salary;
        }

        public void setResponsibility(String responsibility){
            this.responsibility = responsibility;
        }

        public String getResponsibility(){
            return responsibility;
        }

        public void setShareUrl(String shareUrl){
            this.shareUrl = shareUrl;
        }

        public String getShareUrl(){
            return shareUrl;
        }

        public void setCompanyName(String companyName){
            this.companyName = companyName;
        }

        public String getCompanyName(){
            return companyName;
        }

        public void setLogo(String logo){
            this.logo = logo;
        }

        public String getLogo(){
            return logo;
        }

        public void setId(int id){
            this.id = id;
        }

        public int getId(){
            return id;
        }

        public void setJobTitle(String jobTitle){
            this.jobTitle = jobTitle;
        }

        public String getJobTitle(){
            return jobTitle;
        }

        @Override
        public String toString(){
            return
                "DataItem{" +
                "job_type = '" + jobType + '\'' +
                ",country = '" + country + '\'' +
                ",city = '" + city + '\'' +
                ",created_at = '" + createdAt + '\'' +
                ",description = '" + description + '\'' +
                ",requirement = '" + requirement + '\'' +
                ",salary = '" + salary + '\'' +
                ",responsibility = '" + responsibility + '\'' +
                ",share_url = '" + shareUrl + '\'' +
                ",company_name = '" + companyName + '\'' +
                ",logo = '" + logo + '\'' +
                ",id = '" + id + '\'' +
                ",job_title = '" + jobTitle + '\'' +
                "}";
            }
    }

Api Call with retrofit
public void getJobsData() {
        mProgressDialog = new ProgressDialog(getContext());
        mProgressDialog.setIndeterminate(true);
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.show();
        apiInterface.getJobs().enqueue(new Callback<JobRecommendationsResponse>() {
            @Override
            public void onResponse(Call<JobRecommendationsResponse> call, Response<JobRecommendationsResponse> response) {
                    mProgressDialog.dismiss();
                    Log.e("data", response.toString());
                    mProgressDialog.dismiss();

            }

            @Override
            public void onFailure(Call<JobRecommendationsResponse> call, Throwable t) {
                Log.d("Error305", t.getMessage());
                mProgressDialog.dismiss();

            }
        });

    }

My ApiInterface
  package com.example.jobportal.network;

import com.example.jobportal.models.JobRecommendationsResponse;

import retrofit2.Call;
import retrofit2.http.GET;

public interface ApiServices {

    @GET("/api/recommendation")
    Call<JobRecommendationsResponse> getJobs();
}

My ApiClient class
    package com.example.jobportal.network;

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiClient {
    public static final String BASE_URL = "http://private-2232a-testjobs.apiary-mock.com/";

    private static Retrofit retrofit = null;

    public static Retrofit jobsInfo() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

I just want to map the json object from the server to my model object and than use that model object to get the data.


text:
Q: Is there an antiderivative for $e^{-\left( x + \frac{1}{x}\right)}$? I was playing around with some integrals I made up myself and was trying to find a closed-form for

$$
\int_{0}^{t} e^{-\left( x + \frac{1}{x}\right)} \ dx, \qquad t < \infty
$$

I'm aware that if we let $t \to \infty$ then a solution can be obtained in terms of a modified Bessel function, but I couldn't seem to get a result for the finite-limit version.
By plugging the integral into WolframAlpha it replies that the integral above doesn't have an elementary solution. However, I would like to find any possible closed form, even if it's in terms of special functions (which will very likely be necessary if such a closed-form exists).
I tried doing integration by parts, which resulted in the identity
$$
\int_{0}^{t} e^{-\left( x + \frac{1}{x}\right)} \ dx = - e^{-\left( t + \frac{1}{t}\right)}  +\int_{\frac{1}{t}}^{\infty} e^{-\left( u + \frac{1}{u}\right)} \ du
$$
which makes the problem equivalent to finding a solution to $\int_{\tau}^{\infty} e^{-\left( x + \frac{1}{x}\right)} \ dx$, but I again didn't see how this could help much.

Does anyone know any way to get a closed-form for said integral? Or alternatively, is there a way to prove that  $F(t) = \int_{0}^{t} e^{-\left( x + \frac{1}{x}\right)} \ dx$ is "independent" of other special functions, and as such, would need to be defined as its own "new kind" of special function?


text:
Q: How to print multiple lines with prefixes in loop without keeping to put each line repeatedly in python? I want to make this python code smaller because I can't load no more than a million lines in the code when I try to run it. This is an example of the code but I want to print prefixes 1-4 without putting them on a separate line each to save space.
import random
import string

while True:

prefix1 = 'aaaaaaaa'
prefix2 = 'bbbbbbbw'
prefix3 = 'cccccccd'
prefix4 = 'ttttttty'
print prefix1 + (x)[2:66].lower()
print prefix2 + (x)[2:66].lower()
print prefix3 + (x)[2:66].lower()
print prefix4 + (x)[2:66].lower()

Could I code the bottom like this
print prefix1 - prefix4 + (x)[2:66].lower()

A: Put your sequence of prefixes into a convenient sequence (a list, in this case), and iterate through that sequence:
prefix_list = ['aaaaaaaa', 'bbbbbbbw', 'cccccccd', 'ttttttty']
for prefix in prefix_list:
    print(prefix + (x)[2:66].lower())


text:
Q: Trigger Snowflake task when data pushed to Snowflake stage I have 1 snowflake internal stage where I am pushing json files data through snowsql. Then I will run some queries using snowflake UI. Currently its all manual, is there anyway we can trigger snowflake task when I put data on the stage?

A: There's no way to trigger a Snowflake task, only schedule it. You can however prevent the running of a task on a particular schedule based on a condition. Right now, the only condition that is supported is SYSTEM$STREAM_HAS_DATA:
https://docs.snowflake.com/en/sql-reference/functions/system_stream_has_data.html
In any case, you don't need tasks to automate this pipeline. Using streams and tasks is more than is required for this flow. If the Snowflake stage is external (S3, Azure Blob, GCP storage rather than a Snowflake internal stage) you can use Snowpipe to copy newly arriving files into a table.
https://docs.snowflake.com/en/user-guide/data-load-snowpipe.html


text:
Q: Cygwin Scp or Rsync permissions Why is it that whenever I Scp or Rsync files from my Windows machine using cygwin to my Ubuntu server. The copied files will all have no permissions. Rsync doesn't even work because it cannot copy files into the folders which don't have the +x permission.
How do I fix this?

A: It sounds like you need to set the default mask for your login on the Ubuntu side. This determins the default permissions for new files or folders created by any process running as a certain user. You can find what this value is by loging in on a shell and running umask. For example a normal system will probably say 022, which means files get created with permissions of 644.
You could also try adding a -p (or --perms) to your rsync command to force rsync to set it's own permissions insetad of using the defaults.


text:
Q: Regular sending in Telegram bot does not work correctly In parallel with the usual commands in the bot, I am sending information to each user at the user's time.
Problem: the dictionary with user data in the threading_control() function is correct, but in the regular_sending() function (nested function) it is not correct, although the data does not change. That is, when sending, I don't know why, the data in the dictionary is from another user, respectively - the sending goes to the wrong person in the wrong time.
Code:
def get_user_params(user):
    """Return dict with user's data"""
    params = {'id': user[0],
              'name': user[1],
              'send_time': user[2],
              'city': user[3],
              'news_topic': user[4],
              'quantity_news': user[5],
              'status': user[6]
              }
    return params

@aiocron.crontab('* * * * *')
async def threading_control():
    # Get list of tuple with all users
    all_users = db.get_all_users_info()

    for user in all_users:
        # HERE - DATA RIGHT (CORRECT)
        user_params = get_user_params(user)
        print(user_params)
        if user_params['status'] == 1:
            try:
                user_hours_minutes = user_params['send_time'].split(':')
                hours = user_hours_minutes[0]
                minutes = user_hours_minutes[1]

                @aiocron.crontab(f'{minutes} {hours} * * *')
                async def regular_sending():
                    # HERE - DICT WITH ANOTHER USER'S INFO (NOT CORRECT)
                    print(user_params)

loop = asyncio.get_event_loop()

if __name__ == '__main__':
    executor.start_polling(dp, loop=loop)

If I didn't describe something well, please clarify, my English is so bad:)

A: Perhaps your code contains one of the common mistakes late binding closure


text:
Q: Why am I receiving an Invalid Form Body error with Discord API? I'm making a discord bot but when I create a ping command it says the following:
(node:37584) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
embeds[0].footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
    at RequestHandler.execute (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async RequestHandler.push (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
    at async callback (C:\Users\niels\Documents\VsCode Projects\Discord Bots\FlashyBot\commands\misc\ping.js:15:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:37584) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:37584) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My code for ping.js is:
const { MessageEmbed } = require("discord.js")

module.exports = {
    commands: ["ping", 'pong'],
    expectedArgs: "",
    permissionError: '',
    minArgs: 0,
    maxArgs: null,
    callback: async(message, args, text, client) => {
        let pinging = new MessageEmbed()
            .setTitle('Pinging....')
            .setColor("RED")
            .setFooter(client.user.avatarURL(), client.user.username)

        const msg = await message.channel.send(pinging)

        let embed = new MessageEmbed()
            .setTitle('Pong! ')
            .addField("Api Latency", `${Math.floor(message.createdTimestamp - message.createdTimestamp)}ms`)
            .addField("Latency", `${Math.floor(client.ws.ping)}ms`)
            .setColor("LIGHT_GREEN")
            .setFooter(client.user.avatarURL(), client.user.username)
            .setTimestamp()

        msg.edit(embed)
    }
}

Can someone help me with this? I tried doing message.client.user.avatarURL() and also the displayAvatarURL() function but it keeps giving this error

A: Your logs say
 embed.footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https'). embeds[0].footer.icon_url: Scheme "flashybot" is not supported. Scheme must be one of ('http', 'https').
Which seems to indicate the url provided for your icon is incorrect (and does not start with http or https which is required).
I assume this is client.user.avatarURL() which is incorrect, try to replace it with a hard coded picture link and see if it helps. You may have an incorrect value in avatarURL...


text:
Q: How to change a property from Prism EventAggregator Currently, the EventAggregator from Prism only accepts an action, i.e:
_eventAggregator.GetEvent<Message>().Subscribe(Method);

public void Method(string s) { Property = s; }

How do I get it to change a property, instead of calling a method to change it?

A: You can't, it needs to invoke a method by design. You might be able to use a lambda to mimic the effect of setting a property (not in front of a machine right now, I can't try it), but it's still calling a method under the hood.
_eventAggregator.GetEvent<Message>().Subscribe(s => Property=s));

It's also good practice to unregister message handlers when you're finished with them using event.Unsubscribe() as per the Documentation


text:
Q: how to install python pgmagick on windows I m trying to install pgmagick library on windows. I m following the official page:
http://pypi.python.org/pypi/pgmagick/
From there i can notice that i need to install first easy_install,pip, boost and graphicsMagic.
In this page i found easy_install:
http://blog.troygrosfield.com/2010/12/18/installing-easy_install-and-pip-for-python/
In this page i can find pip and boost:
http://www.lfd.uci.edu/~gohlke/pythonlibs/#pgmagick
But i can't figure out how to install magick++. I went to website and download it but it installs just the software and when i try to install pgmagick like this:
 pip install pgmagick
there is an error that i need magick++:
F:\Python27\Scripts>easy_install -ZU pgmagick
Searching for pgmagick
Reading http://pypi.python.org/simple/pgmagick/
Reading http://bitbucket.org/hhatto/pgmagick
Best match: pgmagick 0.5.4
Downloading http://pypi.python.org/packages/source/p/pgmagick/pgmagick-0.5.4.tar
.gz#md5=c10a454331ac1c359b39e50663fd28e4
Processing pgmagick-0.5.4.tar.gz
Running pgmagick-0.5.4\setup.py -q bdist_egg --dist-dir f:\docume~1\alessa~1\imp
ost~1\temp\easy_install-xaypdo\pgmagick-0.5.4\egg-dist-tmp-qu7mji
Traceback (most recent call last):
  File "F:\Python27\Scripts\easy_install-script.py", line 8, in <module>
    load_entry_point('setuptools==0.6c11', 'console_scripts', 'easy_install')()
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
1712, in main
    with_ei_usage(lambda:
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
1700, in with_ei_usage
    return f()
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
1716, in <lambda>
    distclass=DistributionWithoutHelpCommands, **kw
  File "F:\Python27\lib\distutils\core.py", line 152, in setup
    dist.run_commands()
  File "F:\Python27\lib\distutils\dist.py", line 953, in run_commands
    self.run_command(cmd)
  File "F:\Python27\lib\distutils\dist.py", line 972, in run_command
    cmd_obj.run()
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
211, in run
    self.easy_install(spec, not self.no_deps)
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
446, in easy_install
    return self.install_item(spec, dist.location, tmpdir, deps)
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
476, in install_item
    dists = self.install_eggs(spec, download, tmpdir)
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
655, in install_eggs
    return self.build_and_install(setup_script, setup_base)
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
930, in build_and_install
    self.run_setup(setup_script, setup_base, args)
  File "F:\Python27\lib\site-packages\setuptools\command\easy_install.py", line
919, in run_setup
    run_setup(setup_script, args)
  File "F:\Python27\lib\site-packages\setuptools\sandbox.py", line 62, in run_se
tup
    lambda: execfile(
  File "F:\Python27\lib\site-packages\setuptools\sandbox.py", line 105, in run
    return func()
  File "F:\Python27\lib\site-packages\setuptools\sandbox.py", line 64, in <lambd
a>
    {'__file__':setup_script, '__name__':'__main__'}
  File "setup.py", line 74, in <module>
Exception: Magick++ not found

thanks!

A: I recommend you use the precompiled binary packages from the Unofficial Windows Binaries for Python Extension Packages (as mentioned in the pgmagick web page), instead of trying to compile from source which will be quite a complicated process.


text:
Q: After I use dataset,concatenate, dataset.map only act on original data As the title says, I concatenate two dataset and use map function to change value's position and rescale value. Before I use map, all Tensor's shape are
matched, but after using map function, and use for loop iterate dataset to print index, and iteration's break point is on two dataset joint.
I run into this problem in Colab using GPU,
and use Python 3.6, tensorflow-gpu 2.0.0b1
dataset_crop = tf.data.Dataset.from_generator(img_resize_and_crop_genr, (tf.float32, tf.float32),((7,), (48,48,1)))
dataset = dataset.concatenate(dataset_crop)
dataset = dataset.map(lambda label, img_raw: (tf.cast(img_raw, tf.float32)/float(255), label))
for i,(label, img) in enumerate(dataset):
  print(i)

By the way, dataset's total row has 19984 before concatenating

What the concatenate hell..
...
19982
19983
---------------------------------------------------------------------------
InvalidArgumentError                      Traceback (most recent call last)
<ipython-input-26-36305ee0e8ef> in <module>()
----> 1 for i,(label, img) in enumerate(dataset):
      2   print(i)

4 frames
/usr/local/lib/python3.6/dist-packages/six.py in raise_from(value, from_value)

InvalidArgumentError: ValueError: Tensor's shape (7,) is not compatible with supplied shape [48, 48, 1]
Traceback (most recent call last):

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/ops/script_ops.py", line 209, in __call__
    ret = func(*args)

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/data/ops/dataset_ops.py", line 525, in generator_py_func
    values = next(generator_state.get_iterator(iterator_id))

  File "<ipython-input-25-196a9ac04fc0>", line 5, in img_resize_and_crop_genr
    img.set_shape([side_len, side_len,1])

  File "/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py", line 981, in set_shape
    (self.shape, shape))

ValueError: Tensor's shape (7,) is not compatible with supplied shape [48, 48, 1]

     [[{{node PyFunc}}]] [Op:IteratorGetNextSync]

A: The problem is in your from_generator function. When you are passing the output_shapes parameter, a strict checking is done to see whether the output shape is exactly the same shape being generated or not. In your case, you are getting a ValueError stating that it is expecting (48, 48, 1) but (7,) shape got generated.
A similar error can be generated using the following code:
dataset = tf.data.Dataset.from_tensor_slices((np.zeros(19984, dtype=np.float32), np.ones(19984, dtype=np.float32)))

def img_resize_and_crop_genr():
    yield np.zeros((7,)), np.ones((48, 48, 1))

dataset_crop = tf.data.Dataset.from_generator(img_resize_and_crop_genr, (tf.float32, tf.float32),((48,48,1), (7,)))
dataset = dataset.concatenate(dataset_crop)
dataset = dataset.map(lambda label, img_raw: (tf.cast(img_raw, tf.float32)/float(255), label))
for i,(label, img) in enumerate(dataset):
  print(i)

Output:
ValueError: `generator` yielded an element of shape (7,) where an element of shape (48, 48, 1) was expected.

I believe you have interchanged your output_shapes. If that is the case, you can make the correction as:
dataset_crop = tf.data.Dataset.from_generator(img_resize_and_crop_genr,
                                              (tf.float32, tf.float32),((7,), (48,48,1)))

Also, output_shapes is an optional parameter. You can avoid the problem whole together by not passing the parameter as shown below:
dataset_crop = tf.data.Dataset.from_generator(img_resize_and_crop_genr,
                                              (tf.float32, tf.float32))


text:
Q: $\Sigma \ \vdash A \lor B \ \ $ I'm stuck with the following question:

prove or disprove the following:
if $\Sigma \ \vdash A \lor B  \ \ $ then $\ \ \Sigma \ \vdash A \ \ $  or $\ \ \Sigma \ \vdash B $

Thanks.

A: We may refute the "purported rule" with this counterexample.
Let $\Sigma = \{ A \lor B \}$;
clearly : $A \lor B \vdash A \lor B$.
In classical propositional logic, we have that $\Sigma \vdash \varphi$ iff $\Sigma \vDash_{TAUT} \varphi$.
Thus, if the "purported rule" woul be sound, we would have :

$A \lor B \vDash_{TAUT} A$ or $A \lor B \vDash_{TAUT} B$.

Now, we use another property of the tautological consequence relation :

$\sigma \vDash_{TAUT} \varphi$ iff $\vDash_{TAUT} \sigma \rightarrow \varphi$.

Thus, form the above we may conclude :

$\vDash_{TAUT} (A \lor B) \rightarrow A$ or $\vDash_{TAUT} (A \lor B) \rightarrow B$.

But neither $(A \lor B) \rightarrow A$, nor $(A \lor B) \rightarrow B$ are tautologies.


text:
Q: how to change a dimension of array in python? I am a newbie in python. I have a question about the dimension of array.
I have (10,192,192,1) array which type is (class 'numpy.ndarray').
I would like to divid this array to 10 separated array like 10 * (1,192,192,1). but I always got (192,192,1) array when I separate.
How can I get separated arrays as a same dimension type of original one?
below is my code.
b = np.ndarray((a.shape[0],a.shape[1],a.shape[2],a.shape[3]))
print(b.shape)  # (10,192,192,1)

for i in range(a.shape[0]):
b[i] = a[i]
print(b[i].shape)  # (192,192,1), but I want to get (1,192,192,1)

A: Simply use the numpy .reshape() function:
b[i].reshape((1,192,192,1))

Check out the docs here
For example:
>>> x = np.zeros((13,24))
>>> x.shape
(13,24)
>>> x.resize((1,13,24)).shape
(1,13,24)

A: you can reshape it using np.array()
b = np.zeros((192,192,1))
print(b.shape)  #(192, 192, 1)
print(np.array([b]).shape) #(1, 192, 192, 1)


text:
Q: Likelihood at least 2 out of $n$ numbers are visible to each other in $\mathbb{Z}^n$ Two points in $ \mathbb{Z}^n $  are said to be visible to each other, if they can be connected by a straight line, which doesn't intersect any points of $ \mathbb{Z}^n $
In Apostol's book "An introduction to Number Theory" an answer to the problem stated in the title was given for the special case $n = 2$
However I also wonder, if the problem could be generalized to $n > 2$, picking n points at random an checking, if there were at least $2$ points visible to each other.
As always: Any constructive recommendation for literature, comment or answer is appreciated.

A: Partial answer: The probability for two points to be visible from each other in $n$ dimensions is $\frac1{\zeta(n)}$.
I'll interpret "picking two points at random" as follows. Since we're only interested in the relative position of the two points, I'll take the first one to be the origin. Then for any $R\in\Bbb N$ we count how many points in $[-R,R]^n$ are visible from the origin; call this number $N_R$. The quantity asked for is the limit $\lim_{R\to\infty}\frac{N_R}{(2R+1)^n}$. (There are $(2R+1)^n$ points we could have picked in $[-R,R]^n$.)
Note that $(x_1,\ldots,x_n)$ is visible from the origin iff $\gcd(x_1,\ldots,x_n)=1$. So $$\begin{align*}N_R&=(2R+1)^n-1-\#\{0\neq(x_1,\ldots,x_n)\in[-R,R]^n:\gcd(x_1,\ldots,x_n)>1\}\\
&=(2R+1)^n-1-\#\bigcup_{\substack{p\leq R\\p\text{ prime}}}\{(x_1,\ldots,x_n)\in[-R,R]^n:p\mid x_1,\ldots,x_n\}\\
&=(2R+1)^n-1+\sum_{k=2}^R\mu(k)\left(1+2\left\lfloor\frac Rk\right\rfloor\right)^n\qquad
\text{(by inclusion-exclusion)}\end{align*}$$
Note $$\left(1+2\left\lfloor\frac Rk\right\rfloor\right)^n=\left(\frac{2R}k+O(1)\right)^n=\left(\frac{2R}k\right)^n+O\left(\sum_{m=0}^{n-1}\binom nm\left(\frac{2R}k\right)^m\right)$$
and that $\sum_{m=0}^{n-1}\binom nm\left(\frac{2R}k\right)^m\leq n\left(\frac{2R}k\right)^{n-1}\max_m\binom nm=O_n\left(\left(\frac Rk\right)^{n-1}\right)$ so the probability for a point to be visible from the origin becomes
$$\begin{align*}\lim_{R\to\infty}\frac{N_R}{(2R+1)^n}&=1+\lim_{R\to\infty}\left(\frac{2R}{2R+1}\right)^n\sum_{k=2}^R\left(\frac{\mu(k)}{k^n}+O_n\left(\frac1{k^{n-1}R}\right)\right)\\
&=1+\lim_{R\to\infty}\sum_{k=2}^R\frac{\mu(k)}{k^n}+\lim_{R\to\infty}O_n\left(\int_1^R\frac{dx}{x^{n-1}R}\right)\\
&=1+\zeta(n)^{-1}-1+\lim_{R\to\infty}O_n\left(\int_1^R\frac{dx}{xR}\right)\\
&=\frac1{\zeta(n)}.\end{align*}$$


text:
Q: Strange UITextField(only) constraints behaviour on iPad I have a really strange constraints behaviour on iPad. It looks like:

As you can see here ALL elements on the canvas has the same leading and trailing values. But how you can see, the button and labels are correct but textFields. So ONLY textFields constraints are very strange and I cannot fix that. What can be wrong and how can I fix it? I have no idea. Maybe you could help me

Save button trailing constraint


text:
Q: Given two indep standard normal RVs, X and Y, what is $P(X^2 + Y^2 \leq 1)$? Given two standard normal random RVs, X and Y, how do you find $P(X^2 + Y^2 \leq 1)$?
I approached this by integrating the bivariate using polar coordinates as $x^2 + y^2 = 1$. Not sure if this is correct way or if there's a better way.
My approach:
$$
P(X^2 + Y^2 \leq 1) = \frac{1}{2\pi}\int_{0}^{2\pi} \int_{0}^1 \exp(-\frac{1}{2}) dr d\theta \\
= \frac{1}{2\pi}\int_{0}^{2\pi} \exp(-\frac{1}{2}) d\theta \\
= \frac{1}{2\pi} \cdot 2\pi \exp(-\frac{1}{2}) \\
= \exp(-\frac{1}{2})
$$

A: Since $dxdy=rdrd\theta$ we get $$P(X^{2}+Y^{2} \leq 1)$$ $$=\frac 1 {2\pi} \int_0^{2\pi} \int _0^{1} e^{-r^{2}/2} rdrd\theta$$ $$ ={-e^{-r^{2}/2}}|_0^{1}=1-e^{-1/2}.$$


text:
Q: Allowing user to input number of threads and based on the number of threads distribute additions to each thread Im trying to create a program whereby users can enter a range of numbers for eg: 1 and then 10, so 1+2+3+4+5+6+7+8+9+10 will be added, but not directly, they can be separated into threads. So user can input the number of threads, for eg: if its 5 threads, thread 1 will perform 1+2, thread 2 performs 3+4 , thread 3 and so on. Each thread will then add together to come up with a total.
I have done the part where the addition works but im not sure how to separate it into the number of user input threads.

A: You need to somehow keep the index of elements printed to console already, so it could be done by sending a parameter to the run() function which starts from the first element and keeps on to the second thread.
try the following implementation of the code changes:
for (int i=0; i<threadNo; i++)
    {
       MultithreadingSum object = new
       MultithreadingSum(start,end,threadNo,noOfDigits);
       object.run(i*(end/threadNo)); //sending a parameter to run()
    }

public void run(int time) //time variable to start each time run() is called from current place
    {
       int total =0;
       System.out.println("Thread executed");
       for(a = i + time; a <= j/n+time ; a++){
           System.out.print(a +" ");
           total+=a;
       }
       System.out.println(getName() + " is "+ total);
    }


text:
Q: Razor, JQuery and form : how to set and bind DropDownListFor? I'm trying to do something that seems to be a little bit tricky and since i'm a complete beginner in ASP.NET, JQuery and so on, i'm here to have some advices.
I've rceated a formular that is displayed that way :

The code looks like that :

                Room

                Room name

               User

         @for (int i = 0; i < Model._listPerson.Count(); i++) {

                    @Html.EditorFor(m => m._listPerson[i].myValue.isSelected)

                    @Html.DisplayFor(m => m._listPerson[i].myValue.name)
                    @Html.HiddenFor(m => m._listPerson[i].myValue.name)
                    @Html.HiddenFor(m => m._listPerson[i].myKey)

                    @Html.DropDownListFor(m => m.selectedPerson[i], new SelectList(Model._list[i].myValue, "id", "name"))

        }

Assign all selected rooms to user  @Html.DropDownListFor(m => m.useless, new SelectList(Model._list[0].myValue, "id", "name"))

So the aim of what I want to do is to update all the fields "assigned user" to the name of the user that is selected at the bottom of the table. How to do that easily ?
Thanks !

A: Add a class to your DropDownLists in the loop like this:
@Html.DropDownListFor(m => m.selectedPerson[i], new SelectList(Model._list[i].myValue, "id", "name"), new { @class = "ddl" })

Then, add this script to your page:

A: It's ok now, thanks to ataravati. I had to change the solution a little bit. Here is the javascript :

And here is the new version of the code that display the page :

         @for (int i = 0; i < Model._listPerson.Count(); i++) {

                    @Html.CheckBoxFor(m => m._listPerson[i].myValue.isSelected, new { id = "select"+i })

                    @Html.DisplayFor(m => m._listPerson[i].myValue.name)
                    @Html.HiddenFor(m => m._listPerson[i].myValue.name)
                    @Html.HiddenFor(m => m._listPerson[i].myKey)

                    @Html.DropDownListFor(m => m.selectedPerson[i], new SelectList(Model._list[i].myValue, "id", "name"), new { @class = "ddl"+i })

        }

And now, it's working fine ! Thanks !


text:
Q: Why don't we use importance sampling for one step Q-learning? Why don't we use importance sampling for 1-step Q-learning?
Q-learning is off-policy which means that we generate samples with a different policy than we try to optimize. Thus it should be impossible to estimate the expectation of the return for every state-action pair for the target policy by using samples generated with the behavior policy.
Here is the update rule for 1-step Q-learning:
$Q(s_t,a_t) = Q(s_t,a_t) + \alpha [R_{t+1} + \gamma \max_a{Q(s_{t+1},a) - Q(s_t,a_t)}]$
Here is a link to Sutton's RL book in case you want to look something up.

A: It is explained in the book on page 149:

Note that the importance sampling ratio here starts and ends one step
  later than for n-step TD (7.9). This is because here we are updating a state–action pair.  We do not have to care how likely we were to select the action; now that we have selected it we want to learn fully from what happens, with importance sampling only for subsequent actions.

A: One-step Q-learning does not sample forward trajectories, it just takes the maximum value bootstrapped from the estimated action value.
You will notice that in the examples of importance sampling in Monte Carlo control, that the weighting by importance sampling is applied after taking a step. So the weight is always 1.0 for the first step. This is then consistent with having no apparent importance sampling in one-step off-policy bootstrapping methods.
In multi-step Q-learning, e.g. Q($\lambda$) you should notice that taking any action other than the greedy action will zero the weights of further samples from that trajectory that are used to adjust earlier state, action values. That is a form of importance sampling, since the probability of not taking the greedy action in the target policy is zero.
In theory you could also multiply weights of future greedy actions by the inverse probability of selecting them in the behaviour policy - I have not tried that, but I suspect that it mainly just interacts with $\lambda$ and/or increases variance without much benefit. You would also need to track (and average) all the zero-ed adjustments and add them back in . . .

A: Here is the one-step Q-learning update rule as you gave it:
\begin{equation}Q(s_t, a_t) = Q(s_t, a_t) + \alpha \left[ R_{t+1} + \gamma \max_a Q(s_{t+1}, a) - Q(s_t, a_t) \right]\end{equation}
That update rule actually matches exactly what the "target policy" (greedy policy in this case) is doing; we update the $Q$ value for the state-action pair for which we've just obtained a new observation ($s_t, a_t$, with the new observation being $R_{t+1}$) under the assumption that we follow up with the greedy / target policy immediately afterwards (resulting in $\max_a Q(s_{t+1}, a)$). In this equation, the only action that we may not have taken according to the target policy is the action $a_t$, but that's fine because precisely that same action is the one for which we're updating the $Q$-value.

Now suppose that we try writing a multi-step (or two-step) update rule naively, without importance sampling. That would look as follows:
\begin{equation}Q(s_t, a_t) = Q(s_t, a_t) + \alpha \left[ R_{t+1} + \gamma R_{t+2} + \gamma^2 \max_a Q(s_{t+2}, a) - Q(s_t, a_t) \right]\end{equation}
This update rule assumes that our behaviour policy (typically something like $\epsilon$-greedy) was used to select another action $a_{t+1}$, resulting in an additional reward observation $R_{t+2}$ and state $s_{t+2}$. In this update rule, we suddenly have a problem for off-policy learning, because our update rule uses a reward $R_{t+2}$ that is the result of an action $a_{t+1}$ which our target policy may not have selected, and it's a different action ($a_t$) for which we're actually updating the $Q$-value. Using information from "incorrect" actions is fine if it's only used to update $Q$-values for those same "incorrect" actions, but it's not fine if we're using it to update $Q$-values for a different ("correct") action (an action that would also have been selected by the greedy / target policy).

A:
Since a(t) is already determined in 1 step, the importance sampling ratio is 1.


text:
Q: How can I properly move the generated NSManagedObject subclasses into the project? I just generated some NSManagedObject subclasses and Xcode adds them in a very weird position:

The files in the red frame (not hand-drawn) are the generated NSManagedObject subclasses. As you can see, they are not in my target "Math Toolbox", which files are in the green frame.
Therefore, the NSManagedObject subclasses are not being compiled when I build the app.
So I try to drag them into the target, and the result looks so horrible:

There are two sets of these files!
I thought the files outside the target can be deleted. So I deleted it but then the files in the target turned red and has become inaccessible!
This is just a mess!
How can I move the files into the target and also leave no files outside the target?

A: This one has always harassed me!
Simple Steps to follow.
Create the subclass the way you did, it will create the one in red box.
When you create, ensure you put them in a new proper folder -->

Next, delete those in the red box, but do a remove reference -->

Next, add those back, before that, create  a new group, or select the group where you want them to be -->

And select those files -->

The final output -->


text:
Q: Toshiba Satellite L645D screen brightness does not work on Ubuntu 12.04 I've installed Ubuntu 12.04 on my Toshiba Satellite L645D and the screen brightness does not work. Any suggestions?

A: You might want to edit your xorg.conf configuration. In a terminal, type:
sudo cp /etc/X11/xorg.conf /etc/X11/xorg.conf.backup
This will make a backup of your xorg.conf file - just in case :) That being done, type:
gksudo gedit /etc/X11/xorg.conf
and under Section "Device" add the following line:
Option "RegistryDwords" "EnableBrightnessControl=1"
Save and reboot.
Perhaps this already does the trick. In that case, congratulations!

A: I know it is a bit late but I had the exact same problem with my girlfriend's computer, a Toshiba Satellite L645D with Ubuntu 14.04 LTS. I think this fix should also work on this computer model with other Debian-related Distros.
After searching and trying everything in the web I found this page:
Keybinding to change brightness by way of acpi brightness file?
So what I did to fix the problem was open /etc/default/grub with nano (or whatever text editor you may like):
sudo nano /etc/default/grub

And search the line that starts with: GRUB_CMDLINE_LINUX_DEFAULT="(something)"
I don't remember exactly what text it had on the quotes. And make it look like:
GRUB_CMDLINE_LINUX_DEFAULT="acpi_osi=Linux acpi_backlight=vendor"

Then update the grub with:
sudo update-grub

Finally, reboot and that's it!
Hope that helps :D


text:
Q: How to run a c# console application from windows task scheduler on server When publishing my console app from VS2017, it creates a .application file that must be run to launch the program. Once I've placed it on the server, I can start it by CMD command, but the program often asks to be installed whenever I start it and if it does this then the task scheduler won't run it.
I just want to be able to run this project daily from the server without having to mess with it. Thanks.

A: You can do this by taking all the dependent dll's and the following files:

*

*exe

*exe.config

*application

*exe.manifest

These are located in the project folder normally bin\debug. if you add all these in a folder and drop this on the server you should be able to run the exe without having to install.
from here you should just be able to create a task to run regularly.


text:
Q: How to sort and rank and select a unique value? I need to get the rank, from a group of players by sorting using sql query.
i have the query.
query = @"SET @rank=0;
           SELECT player_ID,player_name,HP,@rank:=@rank+1 As Rank
           FROM player_profile ORDER BY HP DESC;"

the problem is i just need the specified player's rank from this query.
Since rank is generated using SQL, i can't use WHERE clause. That will one bring one player from DB, resulting one rank.
I tried to get all of them into a datatable and then filter the single value out of it.
con.Open();
        MySqlDataAdapter dt = new MySqlDataAdapter();
        DataTable tt = new DataTable();
        string query = @"SET @rank=0;
           SELECT player_ID,player_name,HP,@rank:=@rank+1 As Rank
           FROM player_profile ORDER BY HP DESC;";
        MySqlCommand cm1 = new MySqlCommand(query, con);
        dt.SelectCommand = cm1;
        dt.Fill(tt);
        con.Close();
        DataRow[] foundRows = tt.Select("player_name=" + Label2.Text); // Error:Cannot find column ["Column name"]
        foreach (DataRow dr in foundRows)
        {
            Label32.Text = dr["Rank"].ToString();
        }

this is how my table looks
http://pastebin.com/7KWJ9bn3
any help is appreciated.

A: I'm a big proponent of not putting business logic in your SQL which it seems like your doing here. The below code is my updated version of your code which should be logically equivalent without having to do any calculation on the SQL side of things.
I'm not entirely sure what you are trying to achieve (is this example code?) so if you can provide more info I can refine this some more, but again this will do the exact same thing in a "better" fashion.
con.Open();
        MySqlDataAdapter dt = new MySqlDataAdapter();
        DataTable tt = new DataTable();
        string query = @"SET @rank=0;
           SELECT player_ID,player_name,HP
           FROM player_profile ORDER BY HP DESC;";
        MySqlCommand cm1 = new MySqlCommand(query, con);
        dt.SelectCommand = cm1;
        dt.Fill(tt);
        con.Close();
        DataRow[] foundRows = tt.Select("player_name=" + Label2.Text); // Error:Cannot find column ["Column name"]
        int count = 1;
        foreach (DataRow dr in foundRows)
        {
            Label32.Text = count;//dr["Rank"].ToString();
            count++;
        }

A: What about selecting from the resulting table?
string query = @"SET @rank=0;
Select a.Rank from (SELECT player_ID,@rank:=@rank+1 As Rank
   FROM player_profile ORDER BY HP DESC) a where player_ID=@1";


text:
Q: sql using pivot improving performance i am using pivot on my first time.
i don't know how it is working so i don't know how to calculate what would be more efficient.
i want to select various fields in addition to the aggreagated fields,
and use some joins to other table.
where should i locate it? should i put the other fields and joins in the pivot source table?
select dc_id, Mosah_code, **field_x, field_y**, [31] , [32] ,[33], [34]
from (select dc.dc_id, dc.Mosah_code, **field_x, field_y**, dp.Sapak_code, dp.DC_Pprice_after_discount from DcnezekCloudAuction dc
left join DcnezekCloudAuctionParts dp on dc.dc_id = dp.DC_ID and dp.Mosah_code = dc.Mosah_code) as S
pivot
(
sum (DC_Pprice_after_discount)
FOR Sapak_Code IN ([31], [32], [33], [34])
)AS P

Or should I place pivot results in a table and join to itself and other table
select * from DcnezekCloudAuction dc1
left join
(select dc_id, Mosah_code,  [31] , [32] ,[33], [34]
from (select dc.dc_id, dc.Mosah_code, dp.Sapak_code, dp.DC_Pprice_after_discount from DcnezekCloudAuction dc
left join DcnezekCloudAuctionParts dp on dc.dc_id = dp.DC_ID and dp.Mosah_code = dc.Mosah_code) as S
pivot
(
sum (DC_Pprice_after_discount)
 FOR  Sapak_Code IN ([31], [32], [33], [34])
)AS P) piv on dc1.dc_id = piv.dc_id and dc1.Mosah_code = piv.Mosah_code

i will just say that in the future i will add where close to the table DcnezekCloudAuction if it matters...


text:
Q: How to change JSON response on JWT Authentication for WP-API? I have used "JWT Authentication for WP-API" plugin to login and to generate a token.
On the JSON response I have only some data from the wp_users table.
How can I change it to take some others value from wp_usermeta table on response, because I want to know user status level.

A: You need to use the filters jwt_auth_token_before_sign or jwt_auth_token_before_dispatch.
The first filter receives the token data, and a user object.
In another plugin or in your theme, you'd need to call add_filter.
I'm a bit rusty on my Wordpress, and I do not have a WP instance handy to test this out, but this is the general theory:
Basic example:
add_filter('jwt_auth_token_before_sign', 'add_user_info_jwt', 10, 2);

function add_user_info_jwt($token, $user) {

    // fetch whatever information you want from the user, probably using the $user
    // object as starting point.

    $token['roles'] = implode(',', $user->roles);;

    return $token;
}

The $token you receive will have this starting structure and information:
$token = [
            'iss'  => get_bloginfo( 'url' ),
            'iat'  => $issuedAt,
            'nbf'  => $notBefore,
            'exp'  => $expire,
            'data' => [
                'user' => [
                    'id' => $user->data->ID,
                ]
            ]
];


text:
Q: jQuery Address: Certify that user is pressing forward button and not back button EDIT 3:
This jsFiddle works with the plugin, I almost have it.
EDIT 2: I made a fiddle.I can't get the plugin to work there, but maybe it is easier to analyze.

In the webpage I am building, Articles(posts) and new Pages are loaded via Ajax. At the same time when new Ajax-content is loaded, the address bar changes (using jQuery Address plugin).
So a normal navigation would go like this:

       /       /page2       /page3       /article7       /page3       /page4

Please note that in this navigation, no browser button was pressed, when exiting the article7 the website goes back to its prior url which is page3 in this case.
The plugin doesn't detect when the user pressed the back or forward button. I managed to figure out a way to know when the user presses back or forward button:
Each time new content is added and the address is changed I store the new address in an array. If the user presses the back'or'forward button I analise it this way:

if (new_url == penultimate_value_in_array) => Back button pressed (errase
  last value from array)else => Forward button pressed (add new value to array)

This works correctly for this kind of navigation:

       /       /page2       /page3       /page4

In my case, it works perfect for the Back button. However if the user presses Forward from /article7 to /page3 the function will read it as Back. Here is an example to understand what I mean:

user is in /page4 and presses Back -> new_page=/page3 that is equal to penultimate_page_in_array(/page3) => BACK

       /       /page2       /page3       /article7       /page3       /page4

user is in /page3 and presses Back -> new_page=/article7 that is equal to penultimate_page_in_array(/article7) => BACK

       /       /page2       /page3       /article7       /page3

user is in /article7 and presses Back -> new_page=/page3 that is equal to penultimate_page_in_array(/page3) => BACK

       /       /page2       /page3       /article7

user is in /page3 and presses Back -> new_page=/page2 that is equal to penultimate_page_in_array(/page2) => BACK

       /       /page2       /page3

user is in /page2 and presses Forward -> new_page=/page3 that is NOT equal to penultimate_page_in_array(/) => FORWARD

       /       /page2

user is in /page3 and presses Forward -> new_page=/article7 that is NOT equal to penultimate_page_in_array(/page2) => FORWARD

       /       /page2       /page3

user is in /article7 and presses Forward -> new_page=/page3 that IS equal to penultimate_page_in_array(/page3) => BACK (and here the value should be FORWARD)

       /       /page2       /page3       /article7

How can I introduce another statement that would determine that False Back should be Forward?

EDIT:
This is the code I am using, I'm not sure if it will help to resolve the issue but here it is:
var site_url = 'www.mysite.com',
    last_visited_url = '',
    just_visited_url = $.address.baseURL().replace(site_url,''),
    visited_pages_array = [just_visited_url],
    page_number = '';

when visiting new page:
ajax call,then:
last_visited_url = just_visited_url;
page_number = $('a.next_page_link').attr('href').replace(site_url,''); // /page3 for example
$.address.state(site_url).value(page_number);
just_visited_url = page_number;
visited_pages_array.push(just_visited_url);

when loading Article:
ajax call,then:
article_url = $('a.article_title').attr('href').replace(site_url,''); // /article7 for example
last_visited_url = just_visited_url;
$.address.state(site_url).value(article_url);
just_visited_url = article_url;
visited_pages_array.push(just_visited_url);

when existing an Article:
last_visited_url = just_visited_url;
$.address.state(site_url).value(page_number); // This page number is the last page_number value
just_visited_url = page_number;
visited_pages_array.push(just_visited_url);

And this code is executed when the user presses some of the browser butons:
$.address.externalChange(function() {

    var newPage = $.address.baseURL().replace(site_url,'');

    if (visited_pages_array[visited_pages_array.length-2] == newPage) {

        visited_pages_array.splice(visited_pages_array.length-1 , 1);
        console.log('BACK pressed');

    } else if (visited_pages_array.length > 1) {

        visited_pages_array.push(newPage);
        console.log('FORWARD pressed');

    } else {

        console.log('REFRESH pressed');

    }

});

A: The fastest and easiest solution I can think of is the following:
Your problem is that when your "next" and "previous" pages are the same, pressing Forward is detected by your code as Back because the following condition is true:
visited_pages_array[visited_pages_array.length-2] == newPage

I would recommend 2 things in your case:

*

*DO NOT delete the address you just left from visited_pages_array as in:
visited_pages_array.splice(visited_pages_array.length-1 , 1);
that way visited_pages_array will keep a list of all visited pages.

*Create a new "global" variable called current_page_index that will hold the index of  your current page in visited_pages_array which can now hold visited_pages_array.length-1 if you are currently at the last page visited or lower values if you used Back button.
Now all you have to do is change your condition from:
if (visited_pages_array[visited_pages_array.length-2] == newPage)

to:
if (visited_pages_array[current_page_index-1] == newPage)

Notes:

*

*When you detect a Back click - do this: current_page_index--; and when you detect a Forward do: current_page_index++;

*When the user clicks your navigation to move the another page, MAKE SURE to do: visited_pages_array.splice(current_page_index+1 ,visited_pages_array.length-current_page_index-1); (removing all the saved Forwards) before pushing the new address to the end of visited_pages_array. And ofcourse setting current_page_index++;
I hope this is clear enough, I couldn't get your jsFiddle to work so explained as clearly as I can. GL :)
EDIT: another idea taken from the jQuery Address docs: (not sure about this one though)

$.address.externalChange(fn): Binds a function to be executed when the
  address is changed from the browser usually when entering the page or
  using the back and forward buttons. The function receives a single
  event object parameter that contains the following properties: value,
  path, pathNames, parameterNames, parameters and queryString.

which means your function can receive an event object - try alert()ing all it's properties maybe the answer will be lying there
$.address.externalChange(function(ev){
    // loop and alert ev's properties
    for (var p in ev) {
        alert(p + ': ' + ev[p]);
    }
})

A: I am not completely sure about your logic here, but what you are describing sounds like a perfect candidate for html5 pushState (browser history state manipulation) functionality.  Here are a few good summaries:

*

*Reference 1

*Reference 2
Also, here are some good demos from fellow stackoverflow users:
HTML5 History API Demo


text:
Q: LINQ converting date, need to handle bad date I'm using LINQ-to-SQL and need to order by a date field.  The date field is stored as text and could have anything in it since it is user entered data.  I need to handle cases where an invalid date was placed in there.
For example, a date of "02/23/0000" returns:

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

I need to avoid errors and I don't care where an invalid date like this gets sorted to.  The parameters of the project mean I can't modify my source data, only read from it.
Here is an example LINQ statement.
from x in dbo_myTable
orderby Convert.ToDateTime(x.MyDateField)
select x

A: Do you definitely need to perform the ordering in the database? In this situation I would strongly consider pulling all of the data, then performing some conversion in .NET code where you have a great deal more control over what's going on, and then order it still in .NET code.
Ultimately, dealing with screwed up data in this sort of situation is tricky - the more control you have, the better.

A: First is first; why cant you change the database to fix you obviously brokes table structure? Why cant you sanitize input when its going into the database? Why are you not validating user input?
Now for the answer; your only option is attempt to parse the date (with DateTime.TryParse or DateTime.TryParseExact) and set a default value of your choosing if it fails to parse:
from x in dbo_myTable
orderby TryConvertToDateTime(x.MyDateField)
select x

private DateTime TryConvertToDateTime(string dt)
{
   DateTime rtn = DateTime.MinValue; // or whatever you want your default to be
   DateTime.TryParse(dt,out rtn);
   return rtn;
}

A: You can do something like this (Based on your comment that they are all 10 characters)
from x in dbo_myTable
orderby x.MyDateField.Substring(6, 4), x.MyDateField.Substring(0, 2), x.MyDateField.Substring(3, 2)
select x


text:
Q: Python script ImportError: No module named celltool.simple_interface so I'm on a Windows 8 and I'm doing some image analysis for my research. It requires running this python script (I did not write it) called "calculate_distances.py". I am also using CellTool (http://pantheon.yale.edu/~zp2/Celltool/) and Numpy which I have successfully installed.
When I try to run my calculate_distances script, I get this error:
Traceback (most recent call last):
file "calculate_distances.py" line 4, in <module>
import celltool.simple_interface as si
ImportError: No module named celltool.simple_interface

Here is my calculate_distances.py script:
#!/Library/Frameworks/Python.framework/Versions/2.5/bin/python
# Import various celltool modules

import celltool.simple_interface as si
import celltool.contour.contour_class as contour_class
from celltool.utility.path import path
import celltool.utility.datafile as datafile
import numpy

# Designate your working directory - ie, replace '/parent_directory/' with the path that contains your contour files
#parent_dir=path('/parent_directory/')
parent_dir=path('./')

# Identify and load  all of the contour files
contour_files=parent_dir.files('*.contour')
contours=si.load_contours(contour_files)
all_distances=numpy.arange(len(contours[0].points))

# Calculate the normal displacement of the cell boundary at every contour point.
n=1
while n<len(contours):
contour_class.Contour.global_reorder_points(contours[n],contours[n-1])
displacement_vectors = contours[n-1].points - contours[n].points
normals = contours[n-1].inward_normals()
distances  = (normals * displacement_vectors).sum(axis=1)
all_distances=numpy.vstack((all_distances,distances))
n=n+1

# Save a csv file with the normal displacement of the boundary at each contour point (columns) at each time point (rows)
datafile.write_data_file(all_distances,parent_dir/'distances.csv')

I have no idea what the error means, as I'm a first-time programmer. First I thought I needed to install a C++/fortran compiler, so I installed Simple Fortran, but it still does not work. Everything works fine on Mac system (after I installed GNU fortran) but for some reason it's not working on Windows. Is it because my CellTool is not installed in the right location? Or is it something with the script?
Any ideas? Thanks very much for your help!!

A: You have two options then.

*

*Try adding CellTool installation directory to your PYTHONPATH environment variable, if you haven't already (create this variable if necessary).
Search for something like celltool.dll or libcelltool.dll (or even celltool.py). See if it helps. If not :

*Compile the source by following those few steps... Install MinGW (installer here), checking C/C++ (gcc/g++) and Fortran when asked by the installer. Then add C:/MinGW/bin (or whereever you installed MinGW) to your PATH environment variable. Download and unpack CellTool source package from the web site. Finally open a command shell (search for cmd program), change directory to the newly unpacked directory and build by typing :
python setup.py install
This should properly compile and install the celltool python package to the site-packages directory of your Python installation.
Option 2 is the sure/safe (but not easiest, I agree) way to get it work.


text:
Q: built in unix / linux command for recursive find and replace? Many people string together find and sed, or perl, or any number of other unix commands to find and replace across multiple files. But, there's a simple command that can do it for you without the hassle?
Edit:
The Digital Ninja points out that it's rpl.
However this is not a built in command but, for debian based distros like Ubuntu you can simply install it with
    sudo apt-get install rpl
I would guess that it's available through most package managers in other *nix OSs.
OS X Users can download a binary at
http://www.laffeycomputer.com/rpl.html

A: I belive you are thinking of 'rpl'
http://www.linux.org/apps/AppId_2684.html

A: I think some variation of the following would work :
find . -name *.extension | perl -pi.bak -e "s/text_to_be_replaced/replacement/"


text:
Q: How to split a part from a string when a special character is found I have an array of string which looks like this:
ErrStr = [
\\abc\def\ghi;  ,
\\klm\nop\qrs;
]

So, this array of strings will be dynamic, so what I want to extract is only the abc and klm from this array.
This piece of code is what joins the strings after filtering from the data:
let errorArr = filteredError.map(a => a.ErrStr.split('\\\\', '')).join('')

I tried the above code, it cuts the \\ and replaces with , but I am not able to figure out how do I remove the 2nd and 3rd part of the string. Thanks in advance.

A: Backslash in an Escape character in Javascript and has special meaning. To literally use it you need to, well, escape it beforehand with another backslash

const str1 = "\a";
console.log(str1);  // "a"    Where's my backslash?
const str2 = "\\a";
console.log(str2);  // "\a"   Aha, here it is

Therefore, first make sure your array has Strings (which currently what you provided are not strings therefore it's an invalid JSON)
And use:

const arr = [
  "\\\\abc\\def\\ghi;",
  "\\\\klm\\nop\\qrs;",
];

const codes = arr.map(s => /(?<=^\\\\)[^\\]+/.exec(s)).flat()
console.log(codes); // ["abc", "klm"]

Overview example on Regex101.com


text:
Q: What parameters to use to call an unmanaged DLL in powershell (call ok in C program) I've the mydll.dll (unmanaged, no manifest) contains myfun (6 parameters). Some years ago, I've created C program to call it, it's working. Today, I need to call mydll.dll without EXE. I've found in stackoverflow how to do it with Powershell, but when I call myfun there are error about parameters.
Could you help me to have the right syntax to call myfun ?
C program which is working :
typedef int __cdecl (*GLIX)(LPSTR xa, LPINT xalen, LPSTR xb, LPINT xblen, LPSTR xc, LPINT xclen);
char a[256], b[256], c[256];
int alen = 255, blen = 255, clen = 255;
char * mydll;
struct stat s; if (stat(mydll, &s) != 0) return 1; // no mydll
HMODULE hm = LoadLibrary(TEXT(mydll); if (hm == NULL) return 2; // mydll not loaded
GLIX myfun = (GLIX)GetProcAddress(hm, "myfun"); if (myfun == NULL) return 3; // myfun not found
if (myfun(a, &alen, b, &blen, c, &clen) != 0) return 4; // call myfun

My test in Powershell :
# test.ps1
param()
$signature = @'
[DllImport("mydll.dll")]
public static extern uint myfun(string xa, int xalen, string xb, int xblen, string xc, int xclen);
'@
$type = Add-Type -MemberDefinition $signature -Name mydll -Namespace myfun -PassThru
$a = New-Object System.Text.StringBuilder 256; [int]$alen = 255;
$b = New-Object System.Text.StringBuilder 256; [int]$blen = 255;
$c = New-Object System.Text.StringBuilder 256; [int]$clen = 255;
$type::myfun($a, [ref]$alen, $b, [ref]$blen, $c, [ref]$clen)
write-host 'a = ' $a.tostring()
write-host 'b = ' $b.tostring()
write-host 'c = ' $c.tostring()

The error :
    PS C:\XXX> .\test.ps1
    Impossible de convertir l'argument «alen» (valeur «System.Management.Automation.PSReference`1[System.Int32]») de «myfun» en type «System.Int32»: «Impossible de convertir la valeur «
    System.Management.Automation.PSReference`1[System.Int32]» du type «
    System.Management.Automation.PSReference`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral,
    PublicKeyToken=b77a5c561934e089]]» en type «System.Int32».»
    Au caractère C:\XXX\test.ps1:11 : 1
     $type::myfun($a, [ref]$alen, $b, [ref]$blen, $c, [ref]$clen ...
     CategoryInfo          : NotSpecified: (:) [], MethodException
 FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

I understand the trouble is about integer parameters but I don't know how to declare and use them right. Thank for your help. Sorry for any mistake, it's my first post here.Jean-Claude


text:
Q: Load an external JavaScript library into your code and modify parts of the library? I'm trying to load an external JavaScript library into my code:

var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://vcg.isti.cnr.it/3dhop/distribution/js/presenter.js";
$(useTab).append(s);

I know that in the library presenter.js" I need to change some const variables into var. I checked that by downloading a local copy of presenter.js" on my server and making that change. However, I need that library to be loaded from the internet. The question is, can I modify an external JavaScript library and make my program work?
I read elsewhere in StackOverflow that you can try ajax:

$.ajax({
method: 'GET',
dataType: 'text',
url: 'http://vcg.isti.cnr.it/3dhop/distribution/js/presenter.js'
}).then(function(data) { data = data.replace('const
SGL_TRACKBALL_NO_ACTION = 0;', 'var SGL_TRACKBALL_NO_ACTION = 0;')
data = data.replace('const SGL_TRACKBALL_ROTATE = 1;', 'var
SGL_TRACKBALL_ROTATE = 1;')  data = data.replace('const
SGL_TRACKBALL_PAN = 2;', 'var SGL_TRACKBALL_PAN = 2;')  data =
data.replace('const SGL_TRACKBALL_DOLLY = 3;', 'var
SGL_TRACKBALL_DOLLY = 3;')  data = data.replace('const
SGL_TRACKBALL_SCALE = 4;', 'var SGL_TRACKBALL_SCALE = 4;')  eval(data)
})

But I had no luck. I'm new to JavaScript so any help will be appreciated. I'm not sure that what I'm asking is doable though. Thank you in advance!
Edit:
Hi guys and thank you for your responses! Ok, I tried the following:
var scripts = ["spidergl.js", "presenter.js", "nexus.js", "ply.js", "trackball_sphere.js",
    "trackball_turntable.js", "trackball_turntable_pan.js", "trackball_pantilt.js", "init.js"];

for (index = 0; index < scripts.length; index++) {
    scripts[index] = "http://vcg.isti.cnr.it/3dhop/distribution/js/" + scripts[index];
  }

  getScripts(scripts, function () {

    $(document).ready(function () {
      init3dhop();

      setup3dhop(referenceUrl, fileType);

      resizeCanvas(640, 480);

      moveMeasurementbox(70, 243);
      movePickpointbox(70, 301);

      //moveToolbar(20, 20);
    });

  });

Here is the utility function getScripts:
function getScripts(scripts, callback) {
  var progress = 0;
  scripts.forEach(function (script) {
    $.getScript(script, function () {
      if (++progress == scripts.length) callback();
    });
  });
}

So far so good but when I run clowder I get the error:
Uncaught ReferenceError: SpiderGL is not defined

related to presenter.js (which I believe is related to using const instead of var). However, if I refresh the browser a couple of times it eventually works!! When it works no errors show up in the console!
So, I'm trying to understand why this happens. Thanks again for all the help!

A: You can only use the ajax method when the endpoint doesn't have CORS restrictions. Most servers do have such restrictions, so ajax usually won't work.
If you can find a place where the library is hosted which doesn't have such restrictions, you'll be able to use ajax - for example, jsdelivr will permit it:

fetch('https://cdn.jsdelivr.net/npm/@snakesilk/react-presenter@0.2.0/dist/index.min.js')
  .then(res => res.text())
  .then(console.log);

Given the source code, you can then modify it client-side, and finally append the modified code as a <script> tag.
But that's really weird. It would make much more sense to fork the library, make the required modifications, and host the modified script on a server you control.


text:
Q: R optimization to find best fantasy football lineup For my fantasy league, I've always manually done this in excel, but I'd like to code it in R so I can do it easier year to year.
Given my league specific roster requirements of 1 QB, 2 RB, 2 WR, 1 TE, who should I draft to maximize the Points column (projected fantasy points scored), constrained needing the above positions and on spending $200 or less in Value (Value column)?
I usually do this in excel solver to tell me who to draft. I then try to draft those players and if I can't (for example if a player gets bid too high for me to afford), I rerun the solver to show me the next best strategy.
Here is my data in a df:
    > dput(players)
structure(list(Player = c("John1", "John2", "John3", "John4",
"John5", "John6", "John7", "John8", "John9", "John10", "John11",
"John12", "John13", "John14", "John15", "John16"), Position = c("QB",
"QB", "QB", "QB", "RB", "RB", "RB", "RB", "WR", "WR", "WR", "WR",
"TE", "TE", "TE", "TE"), FantasyPoints = c(10, 8, 6, 4, 20, 15,
10, 5, 30, 20, 10, 5, 50, 30, 20, 10), DraftValue = c(15, 10,
8, 2, 50, 30, 25, 20, 40, 30, 20, 10, 50, 35, 20, 5)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -16L))

and here is my code so far:
# Create objective function to maximize fantasy points
obj <- players$FantasyPoints

# Create constraints for number of players at each position
qb_constraint <- players$Position == "QB"
rb_constraint <- players$Position == "RB"
wr_constraint <- players$Position == "WR"
te_constraint <- players$Position == "TE"

# Create constraint for total draft budget
budget_constraint <- players$DraftValue <= 200

# Run linear programming problem
lp_model <- lp("max", obj, qb_constraint, "=", 1, rb_constraint, "=", 2, wr_constraint, "=", 2, te_constraint, "=", 1, budget_constraint, "<=", 200)

# Print optimal solution
print(players[lp_model$solution == 1, ])

But I'm getting an error when running the LP model:
"Error in lp("max", obj, qb_constraint, "=", 1, rb_constraint, "=", 2,  :
unused argument (200)"

A: You need to form const.mat in lpSolve::lp. You can do that using model.matrix:
player_types <- c(QB = 1, RB = 2, WR = 2, TE = 1)
max_cost <- 200

res <- lp(
  direction = "max",
  objective.in = players$FantasyPoints,
  const.mat = rbind(
    t(model.matrix(~Position - 1, players))[paste0("Position", names(player_types)),],
    players$DraftValue
  ),
  const.dir = c(rep("==", length(player_types)), "<="),
  const.rhs = c(player_types, max_cost),
  all.bin = TRUE
)

note that all variables are binary (0 - not selected, 1 - selected). Chosen players and total fantasy points:
chosen_players <- players$Player[res$solution == 1]
chosen_points <- res$objval

A: this is the fix
    # Define the objective function (maximize fantasy points)
obj <- players$FantasyPoints

# Prompt user to input number of QBs
num_qb <- as.numeric(readline("Enter the number of QBs: "))
num_rb <- as.numeric(readline("Enter the number of RBs: "))
num_wr <- as.numeric(readline("Enter the number of WRs: "))
num_te <- as.numeric(readline("Enter the number of TEs: "))
num_value <- as.numeric(readline("Enter your draft budget: "))
num_players <- as.numeric(readline("Adding in your flex spots, enter the total number of starters: "))

# Create a new column indicating the player's position
players$QB <- ifelse(players$Position == "QB", 1, 0)
players$RB <- ifelse(players$Position == "RB", 1, 0)
players$WR <- ifelse(players$Position == "WR", 1, 0)
players$TE <- ifelse(players$Position == "TE", 1, 0)
players$Total <- 1

# Define the constraints (position limits and draft value limit)
con <- matrix(c(
  # QB constraint
  players$QB,
  # RB constraint
  players$RB,
  # WR constraint
  players$WR,
  # TE constraint
  players$TE,
  # Draft value constraint
  players$DraftValue,
  #Total players constraint
  players$Total
), ncol = nrow(players), byrow = TRUE)

# Define the variables for the lp
dir <- c("<=", rep(">=",3),"<=","<=")
rhs <- c(num_qb, num_rb, num_wr, num_te, num_value, num_players)

# Solve the linear program
result <- lp("max", obj, con, dir, rhs, all.bin = TRUE)

# Print the optimal team
print(players[result$solution == 1,])


text:
Q: Remove duplicates from pandas dataframe while keeping majority element I have a pandas Dataframe that looks like this:
   Cat  Date
1  A    2019-12-30
2  A    2019-12-30
3  A    2020-12-30
4  A    2020-01-06
5  A    2020-01-06
6  B    2020-01-06
7  B    2020-01-13
8  B    2020-01-13
9  A    2020-01-13
 .    .
 .    .
 .    .

There are duplicate dates in the Date column, and I want to "smush" down the DataFrame so that all the duplicate dates are removed. However, to determine what's in the "Cat" column after this "smushing", I want to pick the majority element of the dates that are being "smushed".
Thus, I want the output to be:
   Cat  Date
1  A    2019-12-30
2  A    2020-01-06
3  B    2020-01-13
 .    .
 .    .
 .    .

Efficiency is important, I want to be able to do this as quickly as possible, as my DataFrame is quite large (100k rows). There is a guarantee that the number of repeated dates will always be odd, and that the total number of different "Cat" letters can be max 2, so there is no concern of ties.

A: Try value_counts to count all values after a groupby on the date column:
df.groupby("Date").agg(lambda x: x.value_counts().index[0])
#            Cat
# Date
# 2019-12-30   A
# 2020-01-06   A
# 2020-01-13   B
# 2020-12-30   A

Explanations:

*

*Split the dataframe in groups according the Date using groupby.

*Apply an aggregation using agg. This function accepts an function to aggregate the groups.

*Define the aggregation function:
3.1. Get the number of values per group using the value_counts function:
print(df.groupby("Date").agg(lambda x: x.value_counts()))
#                Cat
# Date
# 2019-12-30       2
# 2020-01-06  [3, 2]
# 2020-01-13  [2, 1]
# 2020-12-30       1

Note: the result from the value_counts method is an ordered series.
3.2. However, we actually want the values and not the count. The trick is to use the index on the serie.
print(df.groupby("Date").agg(lambda x: x.value_counts().index))
#                Cat
# Date
# 2019-12-30       A
# 2020-01-06  [B, A]
# 2020-01-13  [B, A]
# 2020-12-30       A

3.3. Finaly, select the first value:
print(df.groupby("Date").agg(lambda x: x.value_counts().index[0]))
#            Cat
# Date
# 2019-12-30   A
# 2020-01-06   B
# 2020-01-13   B
# 2020-12-30   A

A: Here's a simple solution
def removeDuplicatesKeepBest(df):
    # sort the data frame
    df.sort_values(by="Cat")
    # Look only in the date column and only keep the first occurence if there is a dulplicate
    df.drop_duplicates(subset = "Date" , keep = 'first', inplace = True)

    return df

Hope this helps!

A: I'd consider the old groupby
df.groupby(["Cat", "Date"]).size()\
  .reset_index(name="to_drop")\
  .drop("to_drop", axis=1)

Alternatively you can use drop duplicates with two columns
df.drop_duplicates(['Date',"Cat"])


text:
Q: Making up detail view of TableViewController I'm working on a project for iOS5 using xcode.
ARC is ON
Using the storyboard
I have a class named Event which contains event info.
I have a TableView on the storyboard linked to my ListViewController.m file
I also made a view on the storyboard called 'Detail' and a DetailViewController.m file (which it is linked to)
Currently in my ListViewController.m I used this function:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    DetailViewController *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"detail"];
    [self.navigationController pushViewController:detail animated:YES];
}

The items in the listview are made up from a var from the listviewcontroller, named events.
What I want to do is when I init the detailview, I want to pass the event coupled to that list item with it so I can fill up the text from the labels with the correct information in my DetailViewController.m.
I would like to do it like this cause I will also have other representations for the events (on a map, ...) and would like to use this detail view for all of them.
How to best set this up?

A: Add an 'Event' property on your 'DetailViewController' and assign it to the controller before doing the push:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //Get here the selected event fron the datasource and assign it to yourSelectedEvent

    DetailViewController *detail = [self.storyboard instantiateViewControllerWithIdentifier:@"detail"];

    [detail setEvent: yourSelectedEvent];

    [self.navigationController pushViewController:detail animated:YES];
}

Then you can use it to put the text to the labels.


text:
Q: Ubuntu 12.10 + Windows 7 - No option to install alongside windows 7 I have a 64-bit Windows 7 OS installed at the moment. I have used GPartEd to shrink the current Windows 7 partition on my 720GB HDD to 200GB. I have then made a new NTFS partition of 200GB which I will keep for later on as a shared drive between both Windows 7 and Ubuntu.
So in GPartEd I now have 3 partitions which were all automatically there from the Windows 7 installation, I only shrank the 3rd one from the 698GB or so that it was to 200GB and created the 200GB for the shared drive.
I first tried creating another 200GB partition at this stage to install Ubuntu too but when I burnt the DVD and loaded it, Ubuntu gave me no option to install alongside Windows, only the option to erase the entire disk and install Ubuntu on the blank drive...not what I want to do. So I tried installing it through clicking 'Something else', it downloaded all the install files but didn't install. I then had a lot of problems with getting the DVD drive to work and what not but now have this fixed so I can use Windows again.
So now I've used GPartEd to delete the partitions so again I'm now left with the 3 partitions there which Windows 7 automatically installs and a 200GB NTFS partition I will later use as a shared drive.
Booting up from the Ubuntu disc and again there is no option to install alongside Windows 7. How do I get it to do so? All I would like is Windows 7 and Ubuntu on a dual boot, with a 200GB NTFS partition to dump my work onto so that I can access it from both OS's.
Thanks.
EDIT:
/dev/sda1 - fat32 - /boot/efi - 100mb
/dev/sda2 - unknown - 128mb
/dev/sda3 - ntfs - 200gb
/dev/sda4 - ntfs - 297gb
/dev/sda5 - ext4 - / - 191gb
/dev/sda6 - linux-swap - 10gb

A: MBR partitioning scheme only supports 4 primary partitions, once you have all 4 of them you can't create any more of them.
To overcome this limitation, you need to create an extended partition, which can act as a container for a number of logical partitions.
You can then install Ubuntu into a logical partition.

A: I think that if you delete the new partitions and re-expand the Windows 7 partition, it may work. It should ask you to dual boot.