Q: remove Cookie using jquery not working I have two cookies in my JS file and I want to remove them.
I have tried the code below but it is not working
 $.removeCookie('filter', { path: '/Home/' });
 $.removeCookie('Pfilter', { path: '/Home/' });

I have also tried the below for null cookies, but this is also not working.
Thanks for the help
$.cookie('filter',null, { path: '/Home/' });

A: Did you try
$.cookie("name", null);
$.removeCookie('filter', { path: '/' });

A: It might depend on what path your cookie is using. If you goto the chrome developer tools and check the path column under Resources > Cookies > Path.

You might be using the generic / for your path instead of /Home/. Give the code below a try.
To delete a cookie with jQuery set the value to null:
$.removeCookie('filter', { path: '/' });

A: What works for me is setting the cookie to null before removing it:

$.cookie("filter", null);
$.removeCookie("filter);

A: I was having the same issue with jquery version 1.7.1 and jquery cookie version 1.4.1
This was driving me crazy so I decided to dive into the source code and I figured out what is wrong.
Here is the definition of $.removeCookie
$.removeCookie = function (key, options) {
    if ($.cookie(key) === undefined) { // this line is the problem
        return false;
    }

    // Must not alter options, thus extending a fresh object...
    $.cookie(key, '', $.extend({}, options, { expires: -1 }));
    return !$.cookie(key);
};

As you can see when the function checks if the cookie exists it doesn't take the options object into account. So if you are on a different path than the cookie you're trying to remove the function will fail.
A Few Solutions:
Upgrade Jquery Cookies. The most recent version doesn't even do that sanity check.
or add this to you document ready
$.removeCookie = function (key, options) {
    if ($.cookie(key, options) === undefined) { // this line is the fix
        return false;
    }

    // Must not alter options, thus extending a fresh object...
    $.cookie(key, '', $.extend({}, options, { expires: -1 }));
    return !$.cookie(key);
};

or when removing cookies do something like this:
$.cookie('cookie-name', '', { path: '/my/path', expires:-1 });

A: If you use a domain parameter when creating a cookie, this will work
$.removeCookie('cookie', { path: '/' , domain  : 'yourdomain.com'});

A: This simple way it works fine:
$.cookie("cookieName", "", { expires: -1 });


Q: Could not convert parameter `tx` between node and runtime: Could not decode `Call::Assets.0`:Could not decode Execution failed: ApiError("Could not convert parameter `tx` between node and runtime: Could not decode `Call::Assets.0`:\n\tCould not decode `Call::create.3`:\n\t\tNot enough data to fill buffer\n")

Runtime Implementation In Substrate node template vpallet-assets = { default-features = false, version = '3.0.0' }
parameter_types! {
pub const AssetDepositBase: u64 = 1;
pub const AssetDepositPerZombie: u64 = 1;
pub const StringLimit: u32 = 50;
pub const MetadataDepositBase: u64 = 1;
pub const MetadataDepositPerByte: u64 = 1;
pub const AssetDepositPerZombie: Balance = 2 * 7;
pub const AssetDeposit: Balance = 2 * 7 ;
pub const ApprovalDeposit: Balance = 2 * 7 ;
}

impl pallet_assets::pallet::Config for Runtime {

type Event= Event;
type Balance= Balance;
type AssetId= u32;
type Currency = Balances;
type ForceOrigin = frame_system::EnsureRoot<AccountId>;
type StringLimit = StringLimit;
type AssetDepositBase=AssetDepositBase;
type AssetDepositPerZombie= AssetDepositPerZombie;
type MetadataDepositBase = MetadataDepositBase;
type MetadataDepositPerByte = MetadataDepositPerByte;
type WeightInfo = pallet_assets::weights::SubstrateWeight<Runtime>;

}

I am calling the extrinsic from polkadot.js.org (localnode)
In Types using { "Address": "MultiAddress", "LookupSource": "MultiAddress" }
Error Is Not Releated to types MultiAddress, the error is about Call::Assets.0  , I am calling the assets::create extrinsics and all other are working perfectly

A: Close to a duplicate of may other questions here, like this one.
You need to set the types used in your chain in you polkadot.js API consuming apps: https://polkadot.js.org/docs/api/start/types.extend


Q: folium:: make GeoJson search marker transparent I have a basic folium heatmap that shows locations as CircleMarker and a HeatMap layer on top as displayed below.

I wanted to add search functionality in my map so I converted my pandas dataframe into a GeoJson format so that I can pass that.

class folium.plugins.Search(layer, search_label=None,
  search_zoom=None, geom_type='Point', position='topleft',
  placeholder='Search', collapsed=False, **kwargs) Bases:
  branca.element.MacroElement
Adds a search tool to your map.
Parameters:    layer (GeoJson, TopoJson, FeatureGroup, MarkerCluster
  class object.) – The map layer to index in the

I was able to convert my Pandas DataFrame into GeoJson using below code.
df_json = pd.read_csv("C:\\py\\folium\\NE Task 1\\json.csv").dropna(how="any")

# convert lat-long to floats and change address from ALL CAPS to Regular Capitalization
df_json['latitude'] = df_json['latitude'].astype(float)
df_json['longitude'] = df_json['longitude'].astype(float)
df_json['Site Name'] = df_json['Site Name'].str.title()

# we don't need all those columns - only keep useful ones
useful_cols = ['Site ID', 'Site Name', 'latitude', 'longitude']
df_subset = df_json[useful_cols]

# drop any rows that lack lat/long data
df_geo = df_subset.dropna(subset=['latitude', 'longitude'], axis=0, inplace=False)

def df_to_geojson(df_json, properties, lat='latitude', lon='longitude'):

    geojson = {'type': 'FeatureCollection', 'features': []}

    # loop through each row in the dataframe and convert each row to geojson format
    for _, row in df_json.iterrows():
        # create a feature template to fill in
        feature = {'type': 'Feature',
                   'properties': {},
                   'geometry': {'type': 'Point', 'coordinates': []}}

        # fill in the coordinates
        feature['geometry']['coordinates'] = [row[lon], row[lat]]

        # for each column, get the value and add it as a new feature property
        for prop in properties:
            feature['properties'][prop] = row[prop]

        # add this feature (aka, converted dataframe row) to the list of features inside our dict
        geojson['features'].append(feature)

    return geojson

geojson_dict = df_to_geojson(df_geo, properties=useful_cols)
geojson_str = json.dumps(geojson_dict, indent=2)

folium.plugins.Search(data=geojson_dict, geom_type='Point',
                      search_zoom=14, search_label='Site ID').add_to(map)

After doing that search function is working properly as i wanted but a Marker is being displayed on TOP which i cannot hide like below.

Please help me guide how can I hide this marker and keep GeoJson intact so that I can use it for search function. I tried to make it transparent, change the opacity of GeoJson through the solutions I found over stackOverflow but nothing works.
Thanks in advance for your time and sorry for the long post.
Best Regards

A: In general,
if you add folium.LayerControl().add_to(map) to the map then it provides functionality to display or hide your Geojson markers. Then you can hide or display markers using show=False or from 'Layers' icon on the top right of the map (see the image below)
For example:
# creating folium GeoJson objects from out GeoDataFrames
pointgeo = folium.GeoJson(gdf,name='group on map', show=False,
                      tooltip=folium.GeoJsonTooltip(fields=['Name', 'Relation', 'City'], aliases=['Name','Relation', 'City'],
                        localize=True)).add_to(map)

# To Add a LayerControl add below line
folium.LayerControl().add_to(map)

map

Like in these images Marker are shown or hidden by controlling layer from top righ 'Layers' - 1) with markers 2) markers hidden

you can refer to this link for more example:
Folium_search
Hope this helps!!

A: I've found only this solution to make that.
search = folium.FeatureGroup(name="Search", show=False).add_to(map)
geojson_obj = folium.GeoJson(geo_json, zoom_on_click=True).add_to(search)

Search(
    layer=geojson_obj,
    search_label="search_name",
    geom_type="Point",
).add_to(map)

folium.LayerControl().add_to(map)


Q: Forcing error in TypeScript compile with void return With the following code:
function foo() : void {
   // do something
}

var f = foo();  // why no error here?

This does not produce a compiler warning/error even though the foo function has been declared to not return anything.
Another case that I'd like to prevent is:
if (foo()) {

}

I'm building an API to be used by other developers, and TypeScript works well encouraging type safety and often helps to catch common JavaScript errors that otherwise would only be caught in testing rather than at compile time. This case though isn't apparently handled though as it would be in other languages like C#. The developers often will be customers, and may not have as much experience, so I want to make the platform as robust as possible, and catch as many issues before the code is deployed.
Is there some reasonable way to structure the code to prevent other code from attempting to use the undefined result of a function that has no return value? If foo doesn't return anything, I'd rather code only can call it as foo(); and not inadvertently expect a valid return value when doing an assignment (or similar execution).
Other programming languages would often catch this type of code structure at compile time (and display a warning/error).

A: It is because void is a valid TypeScript type declaration. E.g the following is valid
var f:void;

However it is not useful as a variable type.
From the language spec (http://www.typescriptlang.org/Content/TypeScript%20Language%20Specification.pdf):

NOTE: We might consider disallowing declaring variables of type Void as they serve no useful purpose.
  However, because Void is permitted as a type argument to a generic type or function it is not feasible to
  disallow Void properties or parameters.

Update:
As pointed out by Ryan : https://twitter.com/SeaRyanC/status/479664200323579904 You don't get much additional typesafety if f:void was disallowed. You can't use f in a meaningful way e.g. the following are all compile errors.
var f:void;

f.bar; // error
function bar(f:{}){}
bar(f); // error
var baz:{a?:number} = f; // error

// Only allowed cases
f = undefined;
f = null;

Curious about your real world case though.
Update based on question update: Unfortunately I don't see a way to get the compiler to prevent this, since anything is allowed in a JS/TS if statement. Perhaps you want a boolean only truthy/falsy restriction.
if (f()) {

}

A: I believe if you try:
var f:number=foo();

It will return the error you're looking for. I think an untyped variable defaults to "any" which makes it not check typing.
Link here:


Q: Dynamic build a table from json data in angular2 I can't wrap my head around a looping system I need to make to build up a table from json data. This is what I've got so far (tried some other stuff but I think this illustrates it the best way).
Looping through the headers works fine, it's just the cells I can't get to work.
This is my dummy data:
    tableMockData = [
   {
     "header": "TH 1",
      "rows": [
          "TH1 - row1",
          "TH1 -row2",
          "TH1 - row3",
          "TH1 - row4"
      ]
   },
   {
    "header": "TH 2",
     "rows": [
         "TH2 -row1",
         "TH2 - row2",
         "TH2 - row3",
         "TH2 - row4",
     ]
  },
  {
    "header": "TH 3",
     "rows": [
      "TH3 -row1",
      "TH3 - row2",
      "TH3 - row3",
      "TH3 - row4",
     ]
  },
  {
    "header": "TH 4",
     "rows": [
      "TH4 - row1",
      "TH4 - row2",
      "TH4 - row3",
      "TH4 - row4",
     ]
  }
]

This is my basic loop as starting point:

      {{row.rows[i]}}

This is my outcome:

This is my desired outcome:

Can someone point me out in the right direction, I know which cell needs to go where but I simply can't wrap my head around how to loop through it.
Thanks
Update:
here is a stackblitz example:
https://stackblitz.com/edit/angular-cdoqwb

A: Update your Html with below code

    {{row.header}}

   {{row1}}

You do not properly bind your JSON.


Q: Dynamically add new field with same key name in MongoDB Im trying to create a list on one of my collections in a dynamic way, here is an example.
var user = mongoose.Schema({
"NAME": String,
"LAST": String,
"EMAIL": String,
"TasksUploaded": {}

})
And what I want to do in mongoose is update the user with the tasks he has already uploaded, what is the best way to do this? what i want at the end is this:
{
    "Name" : "John",
    "Last" : "Doh",
    "Email" : "john@doh.com",
    "TasksUploaded" : {
        "Task" : "Task A"
        "Task" : "Task B"
        "Task" : "Task H"
        "Task" : "Task F"
        "Task" : "Task C"
    }
}

As you can see the task are not always consecutive and the user can upload them as he wants.
Im new to all this new NoSQL and MongoDB stuff, so if you could tell what is the best practice i would appreciate it.
This is how I currently update it but what happens is that the "Level" gets replaced and y need to add a new line to the docuemnt.
User.findOneAndUpdate({ _id: id}, { $set: { 'TasksUploaded.Task': req.body.task} }, { returnNewDocument: true, new: true }, function (err, result) {
      if (err) {
        console.log("Error saving task: " + err);
        return;
      }
      console.log(result);
    })
  }

A: Nope, that's not possible. You can't have several keys with the same name in an object. Just imagine, how would you address them?
It seems that you need to restructure your data and use arrays.

A: thanks to @Sam,
I modified my structure to add the upload tasks in a form of an array
TasksUploaded ["TaskA","TaskB","TaskC"]
Thank you


Q: Overriding a forms OnPaint method in component class Im looking to override the OnPaint method of the parent form of my component..
However i face 2 errors while doing this, the first is assigning the parent forms event handler

*

*No overload for "OnPaint" matches delegate "PaintEventHandler"

*Member from "Region.FromHrgn(IntPtr)" cannot be accessed with an instance reference; Qualify it with a type name instead.
heres my code
    private Control hostControl;
    public override ISite Site
        {
            get { return base.Site; }
            set
            {
                base.Site = value;
                if (value == null)
                {
                    return;
                }

                IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost;
                if (host != null)
                {
                    IComponent componentHost = host.RootComponent;
                    if (componentHost is ContainerControl)
                    {
                        hostControl = componentHost as ContainerControl;
                        hostControl.FindForm().Paint += new PaintEventHandler(this.OnPaint);
                    }
                }
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            hostControl.Region = hostControl.Region.FromHrgn(CreateTriangle(0, 0, this.Width, this.Height, this.Width, this.Height));
        }

Where am i going wrong?

A: Overriding the OnPaint() method of a control is normally recommended for custom drawing of THAT control, not of drawing another control. What you are trying to do in your code is to attach the Paint event of the hosting form to the OnPaint() method of your control. That's probably not working.
As you can read in the MSDN documentation, the Paint event of a control is raised by the OnPaint() method. You can attach a custom event handler:
hostControl.FindForm().Paint += new PaintEventHandler(Form_Paint);

private void Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
  ...
}

In the PaintEventArgs argument you will get the required parameters for drawing.


Q: Values of array after cudaMemcpy I'd like to know if, when i'm calling cudaMemcpy(...) to get memory on the GPU, also the values inside the array are copied or not. I will explain better: I'm copying the values from one array to another and then i call cudaMalloc and cudaMemcpy.
// Copying values of the arrays
for(int i = 0; i<16; i++){
    array_device_1[i] = array_host_1[i];
    array_device_2[i] = array_host_2[i];
}

// Memory allocation of array_device_1 and array_device_2
cudaMalloc((void**) &array_device_1, SIZE_INT*size);
cudaMalloc((void**) &array_device_2, SIZE_INT*size);

// Transfer array_device_1 and array_device_2
cudaMemcpy(array_device_1, array_host_1, SIZE_INT*size, cudaMemcpyHostToDevice);
cudaMemcpy(array_device_2, array_host_2, SIZE_INT*size, cudaMemcpyHostToDevice);

kernel<<<N, N>>>(array_device_1, array_device_2);

cudaMemcpy(array_host_1, array_device_1, SIZE_INT*size, cudaMemcpyDeviceToHost);
cudaMemcpy(array_host_2, array_device_2, SIZE_INT*size, cudaMemcpyDeviceToHost);

cudaFree(array_device_1);
cudaFree(array_device_2);

So, when i'm executing all those instructions and I'm using all the arrays inside the kernel, are the values inside the array_device_1 and array_device_2 or not ? I tried to print out after the kernel and i noticed that all the arrays are empty! Really i can't understand how i can keep the values inside them and then changing their values with kernel function.

A: Yes they have their values inside. But you can't print them out on the host. For this you will need to copy your data back using
cudaMemcpy((void *) array_host_2, (void *) array_device_2, SIZE_INT*size, cudaMemcpyDeviceToHost);

And then you can print the values of array_host_2.
A bit more explanation: Your array_device_* lives on the GPU and from your CPU (that is printing your output) you do not have direct access to this data. So you need to copy it back to your CPUs memory first before printing it out.

A: Example of copying array with data to device, altering values in kernel, copy back to host and printing the new values:
// Function to run on device by many threads
__global__ void myKernel(int *d_arr) {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    d_arr[idx] = d_arr[idx]*2;
}

int main(void) {
    int *h_arr, *d_arr;
    h_arr = (int *)malloc(10*sizeof(int));
    for (int i=0; i<10; ++i)
        h_arr[i] = i; // Or other values

    // Sends data to device
    cudaMalloc((void**) &d_arr, 10*sizeof(int));
    cudaMemcpy(d_arr, h_arr, 10*sizeof(int), cudaMemcpyHostToDevice);

    // Runs kernel on device
    myKernel<<< 2, 5 >>>(d_arr);

    // Retrieves data from device
    cudaMemcpy(h_arr, d_arr, 10*sizeof(int), cudaMemcpyDeviceToHost);

    for (int i = 0; i<10; ++i)
        printf("Post kernel value in h_arr[%d] is: %d\n", i,h_arr[i]);

    cudaFree(d_arr);
    free(h_arr);
    return 0;
}

A: The code snippet you provided seems correct, other than the first few lines as leftaroundabout pointed out. Are you sure the kernel is correct? Perhaps you are not writing the modified values back to global memory. If you make another set of host arrays and copy the GPU arrays back before running the kernel, are they correct? From what you have, the values inside array_host_* should have been copied to array_device_* properly.

A: You can use a kernel function to directly print values on GPU memory. Use can use something like:
__global__ void printFunc(int *devArray){
      printf("%d", devArray[0]);
}

Hope it helps.


Q: How do I locate data in a database with vague column names? In our database we have a number of tables that have non-descriptive columns names e.g. (Attribute1, Attribute2....Attribute60 etc).
What I am wanting to know is if given a particular piece of information e.g. I know that a  Job Code could be "123456", but I do not know what column in our database relates to Job Code, is it possible using a query to find out which column in which table contains data that is similar to that of 123456?
I am fairly confident my colleague used to have a query to achieve this but he has since left our organisation and I cannot seem to find his query.
Appreciate any help I can get!

A: sp_search_code is what I use to find any code items which are in the DB; however, what you need is a redgate tool which will index the db and help you search its contents.  I will suggest as Just Aguy did, that you spend some time cleaning up those generic column names and any gen table names for that matter, good luck.
http://vyaskn.tripod.com/sql_server_search_stored_procedure_code.htm


Q: how to upload to files to amazon EC2 I am trying to upload files to an amazon EC2 from android. however whenever i go to upload the files I get a Unexpected response code 500 error. From what I uderstand this is because the user doesnt have the correct permissions to upload files to the database? I know that the problem is with the amazon EC2 instance rather than the code. but below is my php code for uploading to the server. first of all is that the correct way to enter the upload folder (/var/www/html/uploads) ? Any help on how i can get this working would be great.
<?php
if(isset($_POST['image'])){
    echo "in";
    $image = $_POST['image'];
    upload($_POST['image']);
    exit;
}
else{
    echo "image_not_in";
    exit;
}

function upload($image){
    $now = DateTime::createFromFormat('U.u', microtime(true));
    $id = "pleeease";

    $upload_folder = "/var/www/html/upload";
    $path = "$upload_folder/$id.jpg";

    if(file_put_contents($path, base64_decode($image)) != false){
        echo "uploaded_success"
    }
    else{
        echo "uploaded_failed";
    }
}

?>

A: Just a few notes:
First, you should make sure to send your data from the app with the enctype of multipart/form-data before submitting to the server.
Second, try variants of this simplified code:
if(isset($_FILES['image']))
{
   $fileTmp = $_FILES['image']['tmp_name'];
   $fileName = $_FILES['image']['name'];

    move_uploaded_file($fileTmp, "/var/www/html/uploads/" . $fileName);
    echo "Success";
}
else
{
    echo "Error";
}

And finally, assuming you're using Apache and the user name is www-data, you'll need to make sure it can write to the upload folder:
sudo chown www-data:www-data /var/www/html/uploads
sudo chmod 755 /var/www/html/uploads


Q: Merge fields laravel collections I have two Laravel collections. Mi first collection called $custom_product:
Collection {#313 ▼
  #items: array:1 [▼
    0 => array:1 [▼
      "custom_description" => "insert description here"
    ]
  ]
}

And I have my other collection called $api_product:
Collection {#311 ▼
  #items: array:29 [▼
    "article_id" => 5570
    "active" => null
    "name" => "CORBATA POLIESTER"
    "detail" => "- Pesa: 43 gr."
    "constructor_name" => "gift"
    "stock_available" => true
    "stock" => null
    "prices" => array:6 [▶]
    "price_pvp" => 29.0
    "size" => "1410X100"
  ]
}

I want this result. The same collection but with the field custom_description added:
Collection {#311 ▼
  #items: array:29 [▼
    "article_id" => 5570
    "active" => null
    "custom_description" => "insert description here"//add this field
    "name" => "CORBATA POLIESTER"
    "detail" => "- Pesa: 43 gr."
    "constructor_name" => "gift"
    "stock_available" => true
    "stock" => null
    "prices" => array:6 [▶]
    "price_pvp" => 29.0
    "size" => "1410X100"
  ]
}

A: You may use put method of
laravel collection.
$collection = collect(['product_id' => 1, 'name' => 'Desk']);

$collection->put('price', 100);

$collection->all();

// ['product_id' => 1, 'name' => 'Desk', 'price' => 100]

A: You can itarete over collections and add fields manually as with simple array:
for ($i = 0; $i < count($secondCollection); $i++) {
    // Add field to an item.
    $secondCollection[$i]['custom_description'] = $firstCollection[$i]['custom_description'];
}

This code will give an idea. Actual code is really depends on collections structure.

A: In the case that you were doing this per individual record using the examples given, I think it would be:
$api_product->put($custom_product->toArray()[0]);

If you wanted to combine multiple records you could use the map() method
$api_products_collection->map(function($key,$item) {
    //combine the record
    return $item;
});


Q: Access parent object of Button in click event in UWP application with C# This is for a UWP application for raspberry pi (c#). I have a button as a public member of a class written by me. Since this is a member of class. Whenever an object of this class is created, it needs to have a Click event. I need to have the click event inside the MainPage.xaml.cs file in order for it to have access to other functions, instead of the actual class.
I am able to use the following code:
ExecutionSequence newSeq = new ExecutionSequence();
newSeq.SelectionButton.Click += SelectionButton_Click;

private void SelectionButton_Click(object sender, RoutedEventArgs e)
{
   Button tempbutton = sender as Button;
}

The above code gives full access of the properties of the Button.
However, I am looking for help in the above scenario to access the actual object of class to which this button belongs to as the event requires to access other members of class.
Please note that I considered making the click event as another member of the class itself. But it makes things complex in my case.


Q: JQuery Mobile clone page I having trouble cloning a page of jqm. Here is an example:
http://jsfiddle.net/QZKBw/
as you can see, the cloning and modifing the page is not the problem:
    var newPage = $('#page-1').clone();
    newPage.prop('id', 'page-2');
    newPage.find('#header-1')
        .prop('id', 'header-2')
        .find('h1')
        .html('Page 2');

The switch back to page 1 will end up with two active pages. Is it a problem with jqm?

A: This should do it: http://jsfiddle.net/Gajotres/Nc98p/
$(function () {
    $('#clone-page').click(function () {
        if($('#page-2').length == 0){
            var newPage = $('#page-1').clone();
            newPage.prop('id', 'page-2');
            newPage.find('#header-1')
                .prop('id', 'header-2')
                .find('h1')
                .html('Page 2');
            newPage.find('#content-1')
                .prop('id', '#content-2')
                .html(' to Page 1');
            newPage.appendTo($.mobile.pageContainer);
        }
        $.mobile.changePage('#page-2');
    });
});


Q: iPhone 5 iOS 8.0 - Forgot my apple ID password & cannot restore the password I received my dad's old iPhone 5. He remembers the password, but he cannot remember his Apple ID's password, nor the security question, nor the password for the email linked to this account. I can access the phone, even jailbreak it, but how can I remove or change the password of the Apple ID?

A: There's no way to reset the password of the Apple ID if you don't know neither the answer to the security question nor the password to the email account linked to the Apple ID.
However, you can easily remove the Apple ID from your iPhone. To do this:

*

*Go to Settings > iCloud.

*At the bottom of the page, tap Delete Account.

*Tap Delete to confirm.

A: The Apple ID is tied to the device's serial number on Apple's servers. You cannot change it without going through Apple. Something that is technically possible, but unethical, is bypassing the Activation Lock (only if you're jailbroken, and I'm not going to cite any references), which will make your device think that it's tied to someone else's account (or no account at all), but that still doesn't change it on Apple's side.


Q: Cannot acces a disposed object I'm trying to change some of my linq codes to sp but in one my functions which is
private async Task getNodes()
{
    List<TreeViewNode> nodes = new List<TreeViewNode>();
    var activities = await _spConnections.GetActiveListBySpAsync(User.Identity.GetCookieUserCompId<int>());

    //Loop and add the Parent Nodes.
    foreach (var activity in activities)
    {
        var model1 = await _activitiesService.GetByIdWithFormsAsync(activity.ID);
        var model = model1.Forms.OrderBy(f => f.Order).ToList();
        var preformid = model1.PreFormId;

        nodes.Add(new TreeViewNode { id = activity.ID.ToString(), parent = "#", text = activity.Name });
        var Forms = await _spConnections.GetSpMainActiveFormListAsync(activity.ID);
        // Loop and add the Child Nodes.
        foreach (var form in Forms)
        {
            DigitalContentEnum enumType = EnumHelper<DigitalContentEnum>.Parse(form.Type);
            string typeName = EnumHelper<DigitalContentEnum>.GetDisplayValue(enumType);

            nodes.Add(new TreeViewNode { id = form.ActivitiesID.ToString() + "-" + form.ID.ToString(), parent = form.ActivitiesID.ToString(), text = form.Title + " (" + typeName + ")  "});
        }

        if (preformid != null)
        {
            var preformtags = await _activitiesService.GetByIdWithPreFormsAsync(preformid);
            var preformModel = preformtags.Forms.OrderBy(x => x.Order).ToList();

            foreach (var foorm in preformModel)
            {
                DigitalContentEnum enumType = EnumHelper<DigitalContentEnum>.Parse(foorm.Type);
                string typeName = EnumHelper<DigitalContentEnum>.GetDisplayValue(enumType);

                nodes.Add(new TreeViewNode { id = foorm.ActivitiesID.ToString() + "-" + foorm.ID.ToString(), parent = model1.ID.ToString(), text = foorm.Title + " (" + typeName + ")  " });
            }
        }
    }

    //Serialize to JSON string.
    var result = JsonConvert.SerializeObject(nodes);
    ViewBag.Json = result;
}

So as you see var activities is being filled by running a sp and it does work
but when it reaches
var model1 = await _activitiesService.GetByIdWithFormsAsync(activity.ID);

The Error:

Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
Object name: 'Context'.

appears
activitesservice is my repository which the runs the following :
public async Task<Activity> GetByIdWithFormsAsync(long id)
{
    return await _activities.Include(x => x.Forms).FirstOrDefaultAsync(x => x.ID == id);
}

and my sp is:
public async Task<List<Form>> GetSpMainActiveFormListAsync(long actId)
{
    var Check = new List<Form>();
    using (_unitOfWork)
    {
        using (var cmd = _unitOfWork.ExecuteCreateConnection())
        {
            cmd.CommandText = "SpGetMainActiveForm";
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            var param1 = cmd.CreateParameter();
            param1.ParameterName = "actId";
            param1.Value = actId;
            cmd.Parameters.Add(param1);

            _unitOfWork.ExecuteOpenConnection();
            using (var result = cmd.ExecuteReader())
            {
                if (result.HasRows)
                {
                    Check = (List<Form>)CommonFunctions.Conversions.MapToList<Form>(result);
                }
            }
            _unitOfWork.ExecuteCloseConnection();
        }
    }
    return Check;
}

UnitOfWork is my repository of my Context which is
public interface IUnitOfWork:IDisposable
{
    EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
    void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class;
    DbSet<TEntity> Set<TEntity>() where TEntity : class;
    int SaveChanges(bool acceptAllChangesOnSuccess);
    int SaveChanges();
    void ExecuteSqlCommand(string query);
    DbCommand ExecuteCreateConnection();
    void ExecuteOpenConnection();
    void ExecuteCloseConnection();
    void ExecuteSqlCommand(string query, params object[] parameters);
    Task<int> SaveChangesAsync(bool acceptAllChangesOnSuccess, CancellationToken cancellationToken = new CancellationToken());
    Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken());
}

and my context is:
public class Context : DbContext, IUnitOfWork
{
    public Context(DbContextOptions<Context> options)
    : base(options)
    {

    }
    public virtual DbSet<Admin> Admin { set; get; }
    public virtual DbSet<Activity> Activities { set; get; }
    public virtual DbSet<ActivityCategory> ActivityCategories { set; get; }
    public virtual DbSet<ActivitiesPic> ActivitiesPics { set; get; }
    public virtual DbSet<ActivityRecord> ActivityRecords { set; get; }
    public virtual DbSet<Answer> Answers { set; get; }
    public virtual DbSet<Company> Companies { set; get; }
    public virtual DbSet<Form> Form { set; get; }
    public virtual DbSet<NazerOrTarah> NazerOrTarah { set; get; }

    //Added in 1398/12/13
    public virtual DbSet<ReportDynamicTemplate> ReportDynamicTemplate { set; get; }
    public virtual DbSet<ReportTemplateForms> ReportTemplateForms { set; get; }

    public virtual DbSet<User> Users { set; get; }
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.HasDefaultSchema("dbo");
        builder.Entity<Activity>()
            .HasIndex(a => a.CompID);

        builder.Entity<ActivityRecord>()
            .HasIndex(a => new { a.ActivitiesID, a.NazerID });

        builder.Entity<Answer>()
            .HasIndex(a => new { a.ActRecordsID, a.FormID });

        builder.Entity<Form>()
            .HasIndex(a => new { a.ActivitiesID, a.ParentId });

        // it should be placed here, otherwise it will rewrite the following settings!
        foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
        {
            relationship.DeleteBehavior = DeleteBehavior.Restrict;
        }

        base.OnModelCreating(builder);
    }

    public void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class
    {
        Update(entity);
    }

    public void ExecuteSqlCommand(string query)
    {
        Database.ExecuteSqlCommand(query);
    }

    public DbCommand ExecuteCreateConnection()
    {
        return Database.GetDbConnection().CreateCommand();
    }

    public void ExecuteOpenConnection()
    {
        Database.OpenConnection();
    }
    public void ExecuteCloseConnection()
    {
        Database.CloseConnection();
    }
    public void ExecuteSqlCommand(string query, params object[] parameters)
    {
        Database.ExecuteSqlCommand(query, parameters);
    }
}

What am I doing wrong?


Q: Set custom default Location and Comment in Printer Properties? This might be an eclectic question, but is there a way to change the default "Location" and "Comment" in printer properties?
I work at a tech place and troubleshoot many various printers. By default, each new printer I test, these fields are blank, and I need to re-type the Location and Comment for each printer that passes QA. I'm hoping there's a registry entry or something that could help with this.
Thanks!

A: This information should be in the registry under the key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Printers\PRINTER-NAME
The values are named :

*

*Description for Comment

*Location for itself


Q: Collecting custom Simple Analytics metadata in a Next.js app I am struggling to collect custom Simple Analytics metadata in my Next.js app. Looking at their docs, I can either set metadata on the window object (link) or add it via a callback function (link).
My Next.js app looks as follows:
_document.js
import Document, { Html, Head, Main, NextScript } from 'next/document'

export default class MyDocument extends Document {
  render() {
    return (

          [...snip...]

    )
  }
}

page.js
import Head from 'next/head'
import { useRouter } from 'next/router'
import Layout from '../components/layout'

export default function Page() {
  const router = useRouter()
  const i = router.query.i

  return (
    <>

        [...snip...]

      // NOTE 1: This does not work

      // NOTE 2: I cannot access `i` here


Q: How to perform a matrix rotation of an information matrix Within the Information Filter, the "inverse" of the Kalman Filter, resides the Information Matrix $Y$, which is itself the inverse of a covariance matrix, $P$, such that $Y=P^{-1}$.
Now, as clarified in this StackExchange question, a covariance matrix can be rotated by a rotation matrix $R_{1\rightarrow2}$ by way of $P_2 = RP_1R^T$. How can this transformation be done entirely in the information space, such that we can use $R$ to get from $Y_1$ to $Y_2$?
The rotation matrix being orthogonal, would the correct method of rotating the information matrix be $Y_2 = R^TY_1R$?

A: In order to find the expression for $Y_2$ as a function of $Y_1$ and $R$ one needs to use that the inverse of a product of matrices requires inverting each of the matrices and reversing the multiplication order, $(A\,B)^{-1}=B^{-1} A^{-1}$, and that the inverse of a rotation matrix is equal to its transpose. Combining this yields that
\begin{align}
Y_2 &= P_2^{-1}, \\
&= (R\,P_1 R^\top)^{-1}, \\
&= R^{-\top}\,P_1^{-1} R^{-1}, \\
&= R\,Y_1 R^\top.
\end{align}


Q: How to manipulate rendered data table that uses a reactive expression? I'm quite new with using Shiny. The code below is actually part of an Rmarkdown file with Shiny coding in it.
I have an issue in handling reactive expressions within Shiny. Basically after calling a reactive expression, I can render or plot the expressions. What I cannot easily do is to manipulate that data after calling it.
I've managed to render and output load_table(). This just tells it to load the csv file on a button click. See code below:
```{r UI inputs}
wellPanel(
  fileInput("dataset", label = "Select a .csv File to upload",
            accept=c("text/csv",
                     "text/comma-separated-values,text/plain",
                     ".csv")),

actionButton(inputId = "loadbutton", label = "Load Data")
)

dataTableOutput("df")

```

```{r Server Functions}
load_table <- eventReactive(input$loadbutton, {
    # input$file1 will be NULL initially. After the user selects
    # and uploads a file, it will be a data frame with 'name',
    # 'size', 'type', and 'datapath' columns. The 'datapath'
    # column will contain the local filenames where the data can
    # be found.
    inFile <- input$dataset

    if (is.null(inFile)){
      return(NULL)}
    else {
      read.csv(inFile$datapath)}
    })

output$df <- renderDataTable({
  load_table()
})
```

My output

An example of a file I loaded

However, once the user selects and loads the data - I can't seem to manipulate it because the reactive expression load_table() doesn't work like a dataframe I'm used to.
What I want to do next is to manipulate load_table() in any way possible. For example, filtering the data by date range or just simply adding additional columns. But I can't seem to manipulate load_table(). And I can't get the table without using a reactive function.
I know there are similar questions already being asked on StackExchange, but it never seems to be what I need. What am I missing here?
Regards
Z


Q: Adding another column to a numpy array I have two arrays of the following dimensions:
a = (6,1) b = (6,4)
I wish to add array (a) as additional column to array (c).
Tried:
c= np.column_stack([b,a])
and get an error due to mismatch of dimensions.

A: Try:
c = np.concatenate((b,a), axis=1)

This assumes that a.shape = (6,1). If a.shape = (6,) then you can do:
c = np.concatenate((b,a.reshape((6,1))), axis=1)


Q: "Wheel of Time", Perrin's PLOD I just came across this term, what does Perrin's PLOD mean? I'm guessing it's during the time he was single-mindedly tring to rescure Faile. But I'm still curious what the PLOD stands for.

A: Plot Line of Doom
According to this website, yes, it does refer to the time he spent trying to rescue Faile.
It may have originated with Leigh Butler, in her WoT rereads. For example:

And the Plotline of Doom officially kicks off. DUN.


Q: Parse html page source with libcurl and C How can I print the source of a webpage, specified in curl_easy_setopt, without html tags? So, printing only the text in the source?

A: Curl/libcurl is just for fetching the HTML page. To extract information from it, you need other tools.
The most general solution is to use a HTML parser. A good one in C is HTMLparser from libxml.


Q: R nls exponential curve I have two vectors X and y2, and I wish to fit an exponential curve to the data.
I tried many approaches described on Stack Overflow topics but all of them give me just a straight line. e.g. I tried this:
model.three <- lm(log(y2) ~ log(X))
plot(X,predict(model.three))
abline(model.three)

My data:
X <- seq(1:50)
Y <- rnorm(50,mean=0,sd=1)
y2 <- exp(X)
y2 <- Y+y2

A: Is this what you are looking for?
model.three <- lm(log(y2) ~ log(X))
plot(X,predict(model.three))

## Instead of abline(), use this:

lines(model.three$fitted.values)

A: Your data expresses an exponential relationship between Y and X, which is Y = exp(X) + eps where eps is some noise.
Therefore, I would suggest fitting a model between log(Y) and X, to capture the linear relationship between the two:
model.three <- lm(log(y2) ~ X)
summary(model.three)
The summary confirms that the relationship captured is as expected (i.e. the coefficient for X is very close to 1).
Since plotting the data on a linear scale will not be useful, I think it is a good idea to plot the fitted straight line with abline.
Note: to be exact, it would be more accurate to capture the relationship between y2 and exp(X), but with your data, the fit is essentially perfect.


Q: Overlay numbers from 0000 to 9999 on a picture I have a picture with some white/blank space. My goal is to automatically generate a number from 0000 to 9999 and put it on top of the picture, then export/save it as a png.
the result should be
mypicture_0000.png
mypicture_0001.png
...
mypicture_9999.png
Has anyone tried something similar?
I am thinking about trying autoit, but will that work? If so which software should I use with autoit?
Thank You.

A: autoit may work.  i'd use python PIL.  i can specify font, convert it to a layer and overlay on top of preexisting image.
EDIT
actually imagemagick can be easier than PIL  http://www.imagemagick.org/Usage/text/

A: Should not be much of a problem if you have Python and the Python Imaging Library (PIL) installed:
from PIL import Image, ImageFont, ImageDraw

BACKGROUND = '/path/to/background.png'
OUTPUT = '/path/to/mypicture_{0:04d}.png'
START = 0
STOP = 9999

# Create a font object from a True-Type font file and specify the font size.
fontobj = ImageFont.truetype('/path/to/font/arial.ttf', 24)

for i in range(START, STOP + 1):
    img = Image.open(BACKGROUND)
    draw = ImageDraw.Draw(img)
    # Write a text over the background image.
    # Parameters: location(x, y), text, textcolor(R, G, B), fontobject
    draw.text((0, 0), '{0:04d}'.format(i), (255, 0, 0), font=fontobj)
    img.save(OUTPUT.format(i))

print 'Script done!'

Please consult the PIL manual for other ways of creating font objects for other font formats


Q: Having trouble sniffing for a DNS response in scapy (Python 3) I currently have this piece of code that is proven to sniff for the DNS query which is defined within DNSsniff(pkt).
I also have a second definition called DNSsniff2(pkt) that tries to sniff for the DNS response, however, I have had little to no luck in getting it to work.
any help would be greatly appriciated :)
import scapy.all as scapy

def DNSsniff(pkt):
    if scapy.IP in pkt:
        ip_src=pkt[scapy.IP].src
        ip_dst=pkt[scapy.IP].dst
        if pkt.haslayer(scapy.DNS) and pkt.getlayer(scapy.DNS.qr) == 1:
            qname=pkt.getlayer(scapy.DNS).qd.qname
            print(str(ip_src) + " -> " + str(ip_dst) + " : " + "(" + str(qname)+ ")")

def DNSsniff2(pkt):
    if scapy.IP in pkt:
        ip_src=pkt[scapy.IP].src
        ip_dst=pkt[scapy.IP].dst
        if pkt.haslayer(scapy.DNS) and pkt.getlayer(scapy.DNS.an) ==1:
            arname=pkt.getlayer(scapy.DNS).an.rdata
            print(str(ip_src) + " -> " + str(ip_dst) + " : " + "(" + str(arname) + ")")

#attempts to capture and filter the nessasery DNS response from the server.
capture = scapy.sniff(iface="Ethernet",filter="udp port 53", store=2, count=2)
print("\nsniffing....")
for i in capture:
    DNSsniff(i)
    DNSsniff2(i)

print("\nsniffing dun")

I have tried to change the scapy.DNS.an to scapy.DNS.rr but the code didnt work


Q: Recyclerview with multiple view types I created a recyclerview with multiple view types.First problem is that images don't show and second problem is when i scroll recyclerview,
values of its items changes and I don't know how can I fix it.
my adapter code:
public class HeterogenousRecyclerviewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{

    private ArrayList<DataObject> mDataset;
    Context context;
    RecyclerView.ViewHolder viewHolder;

    public HeterogenousRecyclerviewAdapter(ArrayList<DataObject> myDataset) {
        this.mDataset = myDataset;
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }

    @Override
    public int getItemViewType(int position) {
        int view_type=mDataset.get(position).getView_type();
        return view_type;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        context=parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());

        switch (viewType){
            case 0:
                View v1 = inflater.inflate(R.layout.layout_viewholder1, parent, false);
                viewHolder = new ViewHolder1(v1);
                break;
            case 1:
                View v2 = inflater.inflate(R.layout.layout_viewholder2, parent, false);
                viewHolder = new ViewHolder2(v2);
                break;
        }

        return viewHolder;
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        switch (viewHolder.getItemViewType()){
            case 0:
                ViewHolder1 vh1 = (ViewHolder1) viewHolder;
                configureViewHolder1(vh1, position);
                break;
            case 1:
                ViewHolder2 vh2 = (ViewHolder2) viewHolder;
                configureViewHolder2(vh2, position);
                break;
        }

    }

    private void configureViewHolder1(ViewHolder1 vh1, int position) {
        if (mDataset != null) {
            vh1.getLabel1().setText(mDataset.get(position).getName());
            //vh1.getLabel2().setText("Hometown: " + user.hometown);
        }
    }

    private void configureViewHolder2(ViewHolder2 vh2, int position) {

        //vh2.getImageView().setImageResource(R.mipmap.img1);
        try {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier(mDataset.get(position).getImg(), "mipmap",
                    context.getPackageName());
            vh2.getImageView().setImageResource(resourceId);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
}

this is my ViewHolder1 class:
public class ViewHolder1 extends RecyclerView.ViewHolder {

    private TextView label1;

    public ViewHolder1(View v) {
        super(v);
        label1 = (TextView) v.findViewById(R.id.text1);
        //label2 = (TextView) v.findViewById(R.id.text2);
    }

    public TextView getLabel1() {
        return label1;
    }

    public void setLabel1(TextView label1) {
        this.label1 = label1;
    }

}

this is ViewHolder1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:textStyle="bold" />

</LinearLayout>

this is ViewHolder2 class:
public class ViewHolder2 extends RecyclerView.ViewHolder {

    private ImageView ivExample;

    public ViewHolder2(View v) {
        super(v);
        ivExample = (ImageView) v.findViewById(R.id.ivExample);
    }

    public ImageView getImageView() {
        return ivExample;
    }

    public void setImageView(ImageView ivExample) {
        this.ivExample = ivExample;
    }
}

this is ViewHolder2.xml:
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ivExample"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:layout_width="200dp"
    android:layout_height="200dp"/>

this is my main activity code:
        ArrayList<DataObject> personList = new ArrayList<DataObject>();
        DataObjectDBAdapter dataObjectDBAdapter = new     DataObjectDBAdapter(getApplicationContext());
        personList = dataObjectDBAdapter.getALL();
        adapter = new HeterogenousRecyclerviewAdapter(personList);

        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
        mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(adapter);

can sb help me?

A: I hadn't saved names of images in the SQLite database so the first problem was because of that, and the second problem was in my adapter code. I had to write "viewHolder" instead of "holder" in onBindViewHolder(), so the correct method is:
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {

    switch (viewHolder.getItemViewType()){
        case 0:
            ViewHolder1 vh1 = (ViewHolder1) viewHolder;
            configureViewHolder1(vh1, position);
            break;
        case 1:
            ViewHolder2 vh2 = (ViewHolder2) viewHolder;
            configureViewHolder2(vh2, position);
            break;
    }

}

A:
First make sure the given statement must only return 0 or 1. because view type must start with 0

int view_type=mDataset.get(position).getView_type();

No need to create the below viewHolder as a member of class
RecyclerView.ViewHolder viewHolder;

Don't check viewType in onBindViewHolder . Instead check holder instanceOf
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        if(holder instanceOf ViewHolder1){
            (ViewHolder1) holder.getLabel1().setText(mDataset.get(position).getName());
        }
        else
        {
            try {
                Resources res = context.getResources();
                int resourceId = res.getIdentifier(mDataset.get(position).getImg(), "mipmap",
                    context.getPackageName());
                (ViewHolder2) holder.getImageView().setImageResource(resourceId);
            } catch (Exception e) {}
        }
    }

A:
i had the same problem values changes after the scroll, then i overide these methods

@Override
public long getItemId(int position) {
    return position;
}

@Override
public int getItemCount() {
    return dataList.size();
},

This solved my problem and  for the Image heck the image resourceId is null or not
   i am not sure if your way is good to set the Resource.

A: While using multiple view types with dynamic data some users may face issues like duplicate data items, data being swapped between questions. To avoid that you have to set a unique view type id for every item.
@Override
public int getItemViewType(int position) {
    // Here you can get decide from your model's ArrayList, which type of view you need to load. Like
    if (list.get(position).type == Something) { // Put your condition, according to your requirements
        return VIEW_TYPE_ONE;
    }
    return VIEW_TYPE_TWO;
}

The above code for getItemViewType can fail where 3 consecutive items will have the same type. For example, if the user enters ans1 in item 1
edit text,ans2 in item 2 edit text, ans3 in item 3 edit text and scroll the recycler view up and down then some users may face issues like duplicate data items, data being swapped between questions.
Formula to create unique view type id :
Formula : pos * Constants.Max + viewType;
set value Constants.Max = 100000;
    class DataAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final int VIEW_TYPE_EDIT_TEXT = 1;
    private final int VIEW_TYPE_IMAGE_VIEW = 2;
    private final ArrayList<DataModel> dataModelArrayList = new ArrayList<>();

    @Override
    public int getItemViewType(int position) {

        String dataType = dataModelArrayList.get(position).getDataType();
        int viewType = VIEW_TYPE_EDIT_TEXT;

        switch (dataType) {
            case "A":
            case "E":
                viewType = VIEW_TYPE_EDIT_TEXT;
                break;

            case "I":
                viewType = VIEW_TYPE_IMAGE_VIEW;
                break;
        }

        int pos = position + 1;
        return pos * Constants.Max + viewType;

    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int type) {

        int count = (int) Math.ceil(type / Constants.Max);
        int viewType = type - count * Constants.Max;

        if (viewType == VIEW_TYPE_EDIT_TEXT) {
            return new ViewHolderTypeEditText(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_et_item, parent, false));
        } else if (viewType == VIEW_TYPE_IMAGE_VIEW) {
            return new ViewHolderTypeImageView(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_sp_item, parent, false));
        }

        return new ViewHolderTypeEditText(LayoutInflater.from(context).inflate(R.layout.adapter_status_prompts_et_item, parent, false));

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int pos) {

        int type = holder.getItemViewType();
        int count = (int) Math.ceil(type / Constants.Max);
        int viewType = type - count * Constants.Max;

        if (viewType == VIEW_TYPE_EDIT_TEXT) {

            DataAdapter.ViewHolderTypeEditText viewHolderTypeEditText = (DataAdapter.ViewHolderTypeEditText) holder;

        } else if (viewType == VIEW_TYPE_IMAGE_VIEW) {

            DataAdapter.ViewHolderTypeImageView viewHolderTypeImageView = (DataAdapter.ViewHolderTypeImageView) holder;

        }

    }

    @Override
    public int getItemCount() {
        return dataModelArrayList.size();
    }

    public class ViewHolderTypeEditText extends RecyclerView.ViewHolder {

        EditText etText;

        public ViewHolderTypeEditText(@NonNull View itemView) {
            super(itemView);

            etText = itemView.findViewById(R.id.et_text);

        }
    }

    public class ViewHolderTypeImageView extends RecyclerView.ViewHolder {

        ImageView imageView;

        public ViewHolderTypeImageView(@NonNull View itemView) {
            super(itemView);

            imageView = itemView.findViewById(R.id.image_view);

        }
    }

}


Q: Laravel groupBy rank resulting in multiple grouped rows I'm using the groupby() function on my query to get some stats on two groups of athletes.
I have a table with my athletes and one with their performance.
- athletes table
-- id
-- name
-- group_id

-performance table
-- id
-- DateTime
-- athlete_id
-- sport_id
-- time

Each athlete do the same sport for multiples days (which is not the same for all athletes). I would like to see the evolution of the time average over days per group in a given sport.
I run this query
$query = '*, AVG(time) as average_time' ;
$Performance = Performance::join('athletes','performance.athlete_id','=','athletes.id')
                            ->select(\DB::raw($query))
                            ->where('performance.sport_id', '=', '43')
                            ->orderBy('group_id', 'asc')
                            ->groupBy('group_id')
                            ->get()
                            ->toArray();

However, this give me the average for a given sport_id but not over each days.
How can I see the average for every day in a given sport groupby group_id?

A: If DateTime is a timestamp then you can use the mysql date functions. Specifically GROUP BY WEEKDAY(timestamp_field).
Added into your query it looks like this
$query = '*, AVG(time) as average_time' ;
$Performance = Performance::join('athletes','performance.athlete_id','=','athletes.id')
                            ->select(\DB::raw($query))
                            ->where('performance.sport_id', '=', '43')
                            ->orderBy('group_id', 'asc')
                            ->groupBy('WEEKDAY(DateTime)')
                            ->groupBy('group_id')
                            ->get()
                            ->toArray();


Q: What type of resistor component is this? I have an RCA Victor 35x tube radio and I need to know what type of resistor this is and what it's purpose is?

There is some wire wrapped around the resistor and it's attached to the antenna.

This is the schematic for the tube radio.

A: that is an air core transformer ... L2 in schematic ... one winding connects to an external antenna and the other winding connects to the internal loop antenna. .... the resistor is for mechanical support


Q: Vue: Setting data from binded prop is using the default value When I pass in name as a prop, it works as expected and sets the nameData data field so that I can change it within the component.
Parent
<child name="charles"></child>

Child
data() {
    return {
        nameData: this.name
    }
},
props: {
     name: {type: String, default: "NONE"}
}

When I bind the prop like below, the nameData data field is set to the default prop, which is "None".  Why is that?
Parent
data() {
   return {
      firstName: "Charles"
  }
}

<child :name="firstName"></child>

Child
data() {
    return {
        nameData: this.name
    }
},
props: {
     name: {type: String, default: "NONE"}
}

A: See my example

*

*First child component works as expected (your code)

*Second displays "NONE" because it's data is initialized with prop value, which is undefined  at the time the (child's) data() is executed. Any change to the prop in the future (in mounted in my example) wont affect child's data...

const child = Vue.component('child', {
  data() {
    return {
      nameData: this.name
    }
  },
  props: {
    name: {
      type: String,
      default: "NONE"
    }
  },
  template: `<div> {{ nameData }} </div>`
})

const vm = new Vue({
  el: "#app",
  components: {
    child
  },
  data() {
    return {
      firstName: "Charles",
      secondName: undefined
    }
  },
  mounted() {
    this.secondName = "Fred"
  }
})

  <child :name="firstName"></child>
  <child :name="secondName"></child>

A: name="charles" - you passed down the string "charles";
:name="firstName" - you passed down a variable "firstName" which seems to be undefined in the parent component at the time of child rendering and the prop in the child component gets the default value you provided it with.
UPD: I played a little with Michal's example. You can use computed instead of data() {} or directly a prop itself if you don't need any data transformation. Because it seems that you assign parent's firstName value in async mode or just later.

const child = Vue.component('child', {
  computed: {
      nameData() {
          return this.name;
      }
  },
  props: {
    name: {
      type: String,
      default: "NONE"
    }
  },
  template: `<div> {{ nameData }} </div>`
})

const vm = new Vue({
  el: "#app",
  components: {
    child
  },
  data() {
    return {
      firstName: "Charles",
      secondName: undefined
    }
  },
  mounted() {
    this.secondName = "Fred"
  }
})

  <child :name="firstName"></child>
  <child :name="secondName"></child>


Q: Robust way of creating formulas in Excel To simplify the problem, let's say I have an Excel sheet which has different numeric values in the cells A1 to B100 (two columns by 100 rows). In column C, I would like to have a formula that will multiply the numbers in A and B for that same row.
The old way I used to write the formula was buy entering in C1 =A1*B1 and then copy the formula down to C100. This worked great but isn't very robust because if someone moves around cells in columns A or B then the formula's will track the new location and mess things up.
Someone then showed me a trick so that this formula could be more robust. I would need to enter in C1 the formula =A:A*B:B this effectively looks at the value in the same row and thus will continue to work as expected when the values in columns A and B are moved around.
Let's assume I now want to create a new calculated value in column D (e.g. value in A for same row + value in column A in previous row) such that the formula in D1 is =A1. The formula in D2 would be =A1+A2 and this formula would then be copied down in column D. This is not as robust, is there a more robust way to do this so that it is immune from the moving around of the source cells (like my first example).
Many thanks in advance

A: You're best option would be using named ranges: a named range can be relative to the cell entered. E.g. if you select cell A2 and insert a name _CellAbovewith the formula=A1(without the$` that are automatically inserted!), you can use CellAbove in any cell to refer to the cell above the cell with the formula.
Therefore for your example, select cell D2 and insert two names (using the Name Manager):
* ColA: =$A2
* ColA_above: =$A1
Then use =ColA+ColA_above as the formula in D2 and copy it down. (Use =ColA in D1).
This will always return you the correct result - and is non-volatile which is really handy in large calculations!
Additional note: For your first example with the multiplication, I'd recommend to simply convert your data to an Excel Table (Insert tab -> Table. Then instead of column A and B, you would have columns, say Price and Quantity- and instead of =A1*B1 you would end up =[@Price]*[@Quantity] when you enter the formula (the same way as usual, i.e. Excel will place those names, no need to worry about it). Now even if you change the sheet strucuter, the formulas will work!

A: If you don't mind using array formulas here, the following, entered as an array formula in the range D2:D100 will work as you ask for:
{=A1:A99 + A2:A100}

(Do not type the curly braces:  highlighting cells D2:D100, typing the formula, and then using Control-Shift-Enter to "confirm/enter" to actualize things will see Excel provide the curly braces around the whole formula.)
This would have worked IN 2013 and does with Excel 2013 today. Of course, today (2023), the {CSE} entry method is not required.
Being an array formula, the cells it references will not change if someone drags and drops a cell from the A1:A100 range. It will simply recalculate for what now exists. So drag A23 and drop it on A12 and A23 will be seen as blank/0 when recalcing and A12 will be seen as having A23's old value when recalcing. The formulas in the array do not change to follow the dragging and dropping.

A: Try this
=INDIRECT("RC1",0)+INDIRECT("R[-1]C1",0)

Note, this has the disadvantage of being Volitile

A: Try this one:
=IF(ROW()=1,OFFSET(B1,0,-1),OFFSET(B1,-1,-1)+OFFSET(B1,0,-1))

The only cell it references is itself so it'll only change that reference if it gets moved and it won't matter, anyway.

A: Or this :
=SUMPRODUCT(A1:A100+A2:A101)

Hopefully I understood you correctly ... :)


Q: Android app security test failed! ... Saying, component is not Protected. An intent-filter exists There is security issue reported from our client about some of the Activity and BroadcastReceiver.
The security test result was talking about
(com.****.*****.Activity / BroadcastReceiver) is
not Protected.
An intent-filter exists.

Thing which is common is that all contains  intent-filter

Please suggest me what should I do?

A: You can set android:exported="false" for the activity in your manifest:

android:exported :
  This element sets whether the activity can be
  launched by components of other applications — "true" if it can be,
  and "false" if not. If "false", the activity can be launched only by
  components of the same application or applications with the same user
  ID. If you are using intent filters, you should not set this element
  "false". If you do so, and an app tries to call the activity, system
  throws an ActivityNotFoundException. Instead, you should prevent other
  apps from calling the activity by not setting intent filters for it.
If you do not have intent filters, the default value for this element
  is "false". If you set the element "true", the activity is accessible
  to any app that knows its exact class name, but does not resolve when
  the system tries to match an implicit intent.
This attribute is not the only way to limit an activity's exposure to
  other applications. You can also use a permission to limit the
  external entities that can invoke the activity (see the permission
  attribute).

<activity
        android:name=".activities.YourActivity"
        android:exported="false" />

You can do same for BroadcastReceiver.


Q: ADF pipeline going into queue state I have a Copy activity where the source and destination are both Blobs.
When i tried the copy pipeline previously,it ran successfully.
But currently it is going into queue state for a long time i.e. 30 minutes.

Can i know the reason behind it?

A: This is not an answer/solution to the problem. Since i cannot comment yet, had to put it in the Answer section. It could be delay in assigning the compute resources. Please check the details.
You can check the details by hovering mouse pointer between Name and Type beside Copy.


Q: Generating Random Number In Each Row In Oracle Query I want to select all rows of a table followed by a random number between 1 to 9:
select t.*, (select dbms_random.value(1,9) num from dual) as RandomNumber
from myTable t

But the random number is the same from row to row, only different from each run of the query. How do I make the number different from row to row in the same execution?

A: you don’t need a select … from dual, just write:
SELECT t.*, dbms_random.value(1,9) RandomNumber
  FROM myTable t

A: Something like?
select t.*, round(dbms_random.value() * 8) + 1 from foo t;

Edit:
David has pointed out this gives uneven distribution for 1 and 9.
As he points out, the following gives a better distribution:
select t.*, floor(dbms_random.value(1, 10)) from foo t;

A: If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:
SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL

A: At first I thought that this would work:
select DBMS_Random.Value(1,9) output
from   ...

However, this does not generate an even distribution of output values:
select output,
       count(*)
from   (
       select round(dbms_random.value(1,9)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   62423
2   125302
3   125038
4   125207
5   124892
6   124235
7   124832
8   125514
9   62557

The reasons are pretty obvious I think.
I'd suggest using something like:
floor(dbms_random.value(1,10))

Hence:
select output,
       count(*)
from   (
       select floor(dbms_random.value(1,10)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   111038
2   110912
3   111155
4   111125
5   111084
6   111328
7   110873
8   111532
9   110953


Q: "Possible multiple enumeration of IEnumerable" issue? I'm getting a Possible multiple enumeration of IEnumerable with Resharper and I'm trying to find out if it's really an issue or not. This is my method:
public IEnumerable<Contact> GetContacts(IContactManager contactManager, string query)
{
    IEnumerable<Contact> contacts = contactManager.GetContacts(query);
    if (contacts.Any()) return contacts; // Get the warning on this line
    // Do some other stuff
    return new[] {
        new Contact { Name = "Example" }
    }
}

Should be obvious, but I'm doing a search for Contact and if the search returns no results I'm returning an array of default values. The consumer should just receive a list which can be enumerated, not modified.
Where is the "multiple enumeration" here? And if there is indeed one, is this not the best type to use in the situation?

A: The multiple enumeration potential is you calling Any, which will cause the first enumeration, and then a potential second enumeration by the caller of that method.
In this instance, I'd guess it is mostly guaranteed that two enumerations will occur at least.
The warning exists because an IEnumerable can disguise something expensive such as a database call (most likely an IQueryable), and as IEnumerable doesn't have caching as part of it's contract, it will re-enumerate the source fresh. This can lead to performance issues later on (we have been stung by this a surprising amount and we don't even use IQueryable, ours was on domain model traversal).
That said, it is still only a warning, and if you are aware of the potential expense of calling an enumerable over potentially slow source multiple times then you can suppress it.
The standard answer to caching the results is ToList or ToArray.
Although I do remember making an IRepeatable version of IEnumerable once that internally cached as it went along. That was lost in the depths of my gratuitous code library :-)

A: Enumerable.Any executes the query to check whether or not the sequnce contains elements. You could use DefaultIfEmpty to provide a different default value if there are no elements:
public IEnumerable<Contact> GetContacts(IContactManager contactManager, string query)
{
    IEnumerable<Contact> contacts = contactManager.GetContacts(query)
        .DefaultIfEmpty(new Contact { Name = "Example" });
    return contacts;
}

Note that this overload is not supported in LINQ-To-SQL.


Q: Filtering with two conditions - Remove duplicates less than a certain value while keeping the original I have a table

total
type

23
Original

3
Duplicate

11
Duplicate

5
Original

16
Duplicate

4
Duplicate

I want to Filter the df['total'] column for only values greater than 10, however, I want to remove only the Duplicates less or equal than 10. So if an Original row is less than 10 it can still be in the df.
This is my Desirable output:

total
type

23
Original

11
Duplicate

5
Original

16
Duplicate

I tried this:
df[(df['total'] > 10) & df['type'] == "Duplicate"]

is not working.
Any idea?

A: The conditions should be enclosed in parentheses, on the right you have square ones. And to get what you showed. You need to add a condition(df['type'] =="Original"), in my opinion.
a = df[(df['total'] > 10) & (df['type'] == "Duplicate")|(df['type'] == "Original")]
print(a)

Output a
   total       type
0     23   Original
2     11  Duplicate
3      5   Original
4     16  Duplicate


Q: Firebase do not return ascending order as expected by using orderByKey I have some data which stored on Firebase by using timestamp as its key value,
but I cannot get all of them by sorting it with orderByKey as expected: returning value do not back in ascending order.
My JSON structure looks like:
{
  "1476986154" : {
    "Cons" : {
      "Black" : 91.531099,
      "Cancel" : 98.832554,
      "Happy" : 97.104925,
      "Pair" : 95.515542
    },
    "Fairy" : {
      "Apple" : {
        "Chair" : {
          "Area" : 1,
          "Count" : 96,
          "Teen" : 0.162139,
          "Score" : 95.16093
        },
        "Fake" : {
          "Area" : 3,
          "Count" : 98,
          "Teen" : 0.683259,
          "Score" : 98.249105
        }
      },
      "Dark" : {
        "Lake" : {
          "Read" : {
            "Height" : 0,
            "Width" : 0,
            "X" : 0,
            "Y" : 0
          }
        },
        "Red" : {
          "Read" : {
            "Height" : 0,
            "Width" : 0,
            "X" : 0,
            "Y" : 0
          }
        }
      }
    },
    "PhotoName" : "oo",
    "Versions" : {
      "Library" : "5.5.6.6"
    }
  },
  "1477280739" : {
    "Cons" : {
      "Black" : 96.389055,
      "Cancel" : 98.265668,
      "Happy" : 93.661556,
      "Pair" : 91.361142
    },
    "Fairy" : {
      "Apple" : {
        "Chair" : {
          "Area" : 1,
          "Count" : 100,
          "Teen" : 0.171286,
          "Score" : 90.849593
        },
        "Fake" : {
          "Area" : 3,
          "Count" : 99,
          "Teen" : 0.200965,
          "Score" : 92.367154
        }
      },
      "Dark" : {
        "Lake" : {
          "Read" : {
            "Height" : 0,
            "Width" : 0,
            "X" : 0,
            "Y" : 0
          }
        },
        "Red" : {
          "Read" : {
            "Height" : 0,
            "Width" : 0,
            "X" : 0,
            "Y" : 0
          }
        }
      },
    },
    "Name" : "pp",
    "Versions" : {
      "Library" : "5.5.6.6"
    }
  }
}

It returns me the largest one first(1490034200), then from smallest to second-largest value(from 1476510510 to 1488805137).
Which confused me since I need to know if the callback is going to the last now.
Code is here: I just query for last data before query for all data with same ValueEventListener:
DatabaseReference.orderByKey().limitToLast(recordQty).addValueEventListener(valueEventListener);
//...
DatabaseReference.orderByKey().addValueEventListener(valueEventListener);

Can anyone understand why this attempt not work?

Here's how my listener looks:
private class ValueEventOnChangeListener implements ValueEventListener {

        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (mDataArrayList == null) {
                mDataArrayList = new ArrayList<>();
            } else {
                mDataArrayList.clear();
            }

            getDataChange(dataSnapshot);

            if (mListener != null) {
                mListener.success(mDataArrayList);
            }
        }

        private void getDataChange(DataSnapshot dataSnapshot){
            try {
                if (mSubDataType == null){
                    for (DataSnapshot data : dataSnapshot.getChildren()){
                        long timestamp = Long.parseLong(data.getKey());
                        mDataArrayList.add(timestamp);
                    }
                }
            }
            catch (Exception e){
                Log.e(TAG, "onDataChange Exception: " + e.toString());
            }
        }
}

A: I can't reproduce the problem.
If I run this snippet of code:
myRef.orderByKey().addValueEventListener(new ValueEventListener() {

    public ArrayList<Long> mDataArrayList;

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (mDataArrayList == null) {
            mDataArrayList = new ArrayList<>();
        } else {
            mDataArrayList.clear();
        }

        getDataChange(dataSnapshot);

        System.out.println(mDataArrayList);

    }

    private void getDataChange(DataSnapshot dataSnapshot){
        try {
            for (DataSnapshot data : dataSnapshot.getChildren()){
                long timestamp = Long.parseLong(data.getKey());
                mDataArrayList.add(timestamp);
            }
        }
        catch (Exception e){
            System.err.println("onDataChange Exception: " + e.toString());
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

With this JSON:
{ "1476986154" : true, "1477280739" : true }

It prints:
[1476986154, 1477280739]

Which seems the correct order to me since 1476986154 < 1477280739.


Q: cancancan manage a relationship Rails I am running into an issue with the cancancan gem for rails
gem 'cancancan', '~> 1.10'

I have four models: User, Company, Locations, Groups
User: Belongs to Company
Company: Has many Locations
Location: Belongs to company
Group: Belongs to Location
In the abilities model I have this:
can :manage, Group, :location => {:id => user.company.locations.map{|l| l.id}}

When creating a new group I am denied (don't have access)
I am looking for the correct way to allow a User to create a group with one of the companies location id's (NOTE: Without cancancan on this all works and all ID's are related and so on).

A: To make sure I'm understanding your question completely...
You're looking for a way to limit a User's ability to manage Groups based on the locations of the Company that User belongs to?
Assuming I've got that correct, I would recommend using #pluck:
can :manage, Group, location_id: user.company.locations.pluck(:id)

This collects all the :id's on a User's Company's Locations, and ensures a User can only manage Groups that have a :location_id contained within that collection.
Functionally, this is identical to what you've done, but is more efficient in two ways:

*

*It doesn't involve any unnecessary Ruby logic

*Using #pluck only queries the :id on a location, as opposed to the entire location and all its attributes
Generally speaking, whenever you're accessing your database in Rails, you're better off doing so entirely with ActiveRecord methods. This will help prevent you from wasting time querying for extra information you don't need, and eliminate the extra overhead of using Ruby to re-structure your data.
Hope that helps!


Q: Celery receives periodic tasks but doesn't execute them I use celery to run periodic tasks in my Django DRF app. Unfortunately, registered tasks are not executed.
Project structure:
project_name
___ cron_tasks
______ __init__.py
______ celery.py

celery.py:
app = Celery('cron_tasks', include=['cron_tasks.celery'])
app.conf.broker_url = settings.RABBITMQ_URL
app.autodiscover_tasks()
app.conf.redbeat_redis_url = settings.REDBEAT_REDIS_URL
app.conf.broker_pool_limit = 1
app.conf.broker_heartbeat = None
app.conf.broker_connection_timeout = 30
app.conf.worker_prefetch_multiplier = 1

app.conf.beat_schedule = {
    'first_warning_overdue': {
        'task': 'cron_tasks.celery.test_task',
        'schedule': 60.0, # seconds
        'options': {'queue': 'default', 'expires': 43100.0}
    }
}

@shared_task
def test_task():
    app.send_task('cron_tasks.celery.test_action')

def test_action():
    print('action!') # print is not executed

    # I also tried to change the data, but it never happens too.
    from django.contrib.auth import get_user_model
    u = get_user_model().objects.get(id=1)
    u.first_name = "testttt"
    u.save()

setting.py:
RABBITMQ_URL = os.environ.get('RABBITMQ_URL')
REDBEAT_REDIS_URL = os.environ.get('REDBEAT_REDIS_URL')
CELERY_BROKER_URL = os.environ.get('RABBITMQ_URL')
CELERYD_TASK_SOFT_TIME_LIMIT = 60
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_RESULT_BACKEND = os.environ.get('REDBEAT_REDIS_URL')
CELERY_IMPORTS = ("cron_tasks.celery", )

from kombu import Queue
CELERY_DEFAULT_QUEUE = 'default'
CELERY_QUEUES = (
    Queue('default'),
)
CELERY_CREATE_MISSING_QUEUES = True
redbeat_redis_url = REDBEAT_REDIS_URL

Rabbitmq is running properly. I can see it's there in the celery worker terminal output:
- ** ---------- .> transport:   amqp://admin:**@localhost:5672/my_vhost

Redis is pinging well. I use redis to send beats.
I run:
celery beat -S redbeat.RedBeatScheduler -A cron_tasks.celery:app  --loglevel=debug

It shows:
[2019-02-15 09:32:44,477: DEBUG/MainProcess] beat: Waking up in 10.00 seconds.
[2019-02-15 09:32:54,480: DEBUG/MainProcess] beat: Extending lock...
[2019-02-15 09:32:54,481: DEBUG/MainProcess] Selecting tasks
[2019-02-15 09:32:54,482: INFO/MainProcess] Loading 1 tasks
[2019-02-15 09:32:54,483: INFO/MainProcess] Scheduler: Sending due task first_warning_overdue (cron_tasks.celery.test_task)
[2019-02-15 09:32:54,484: DEBUG/MainProcess] cron_tasks.celery.test_task sent. id->f89083aa-11dc-41fc-9ebe-541840951f8f

Celery worker is run this way:
celery worker -Q default -A cron_tasks.celery:app -n .%%h --without-gossip --without-mingle --without-heartbeat --loglevel=info  --max-memory-per-child=512000

It says:
-------------- celery@.%me.local v4.2.1 (windowlicker)
---- **** -----
--- * ***  * -- Darwin-16.7.0-x86_64-i386-64bit 2019-02-15 09:31:50
-- * - **** ---
- ** ---------- [config]
- ** ---------- .> app:         cron_tasks:0x10e2a5ac8
- ** ---------- .> transport:   amqp://admin:**@localhost:5672/my_vhost
- ** ---------- .> results:     disabled://
- *** --- * --- .> concurrency: 4 (prefork)
-- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
--- ***** -----
 -------------- [queues]
                .> default          exchange=default(direct) key=default

[tasks]
  . cron_tasks.celery.test_task

[2019-02-15 09:31:50,833: INFO/MainProcess] Connected to amqp://admin:**@127.0.0.1:5672/my_vhost
[2019-02-15 09:31:50,867: INFO/MainProcess] celery@.%me.local ready.
[2019-02-15 09:41:46,218: INFO/MainProcess] Received task: cron_tasks.celery.test_task[3c121f04-af3b-4cbe-826b-a32da6cc156e]   expires:[2019-02-15 21:40:05.779231+00:00]
[2019-02-15 09:41:46,220: INFO/ForkPoolWorker-2] Task cron_tasks.celery.test_task[3c121f04-af3b-4cbe-826b-a32da6cc156e] succeeded in 0.001324941000000024s: None

Expected behavior:
This should run my test_action().
But, even though the celery worker output says succeeded in 0.001324941000000024s, the function never executes.


Q: Hypergeometric conditional probability Question:
Bowl 1 contains 8 red and 6 black marbles. Four marbles are randomly selected from bowl 1 and placed in bowl 2. Then one marble is randomly selected from bowl 2.
What is the probability that two red and two black marbles are selected from bowl 1, given that 1 black marble is selected from bowl 2?
$\Large \frac{\frac{{6 \choose 2}{8 \choose 2}}{{14 \choose 4}}}{\frac{{6 \choose 1}{8 \choose 3}+{6 \choose 2}{8 \choose 2}+{6 \choose 3}{8 \choose 1}+{6 \choose 4}}{{14 \choose 4}}}$
$= \Large\frac{420}{931}$
I don't think this is correct but any help would be much appreciated.

A: Close, but not quite.
You have  calculated the probability that two red and two black marbles were selected from bowl one, given that one of the marbles so selected was black.   That isn't quite what you want.
You want the probability that that two red and two black marbles were selected from bowl one (into bowl two), when given that one black marble was subsequently selected from bowl two.   That is not actually the same condition.

Knowing that "one black marble was drawn from bowl 2" is not the same as knowing that "at least one black marble was placed into bowl 2".   You know more information!   You know that "at least one black marble was placed into the bowl and that one of these was selected".   That extra information affects the conditional probability.

Now, how do you think you might take this condition into account?

Let $A=2$ be the event that two black marbles were selected from bowl one; and $B=1$ the event that a black marble was then selected from bowl two.   Then using conditional probability (Bayes' Rule):
$$\begin{align}P(A=2\mid B=1) & = \frac{P(A=2)\mathsf P(B=1\mid A=2)}{\sum_{n=0}^{4}P(A=n)\mathsf P(B=1\mid A=n)}\end{align}$$
Remember, if you transfer $n$ black marbles into bowl two, there is a $\tfrac n 4$ probability of selecting one of them again.   That is $\mathsf P(B=1\mid A=n)= \tfrac n 4$
So $\mathsf P(A=n)\mathsf P(B=1\mid A=n) = \frac{\binom{6}{n}\binom{8}{4-n}}{\binom{14}{4}}\frac{n}{4}$


Q: REGEX validação de senha Tenho um problema de Validação e não consigo aplicar dentro de uma estrutura simples, 3 validações não pode ter alfanuméricos  decrescentes, crescentes e nem repetidos numa mesma senha.

Por exemplo: 00000000 , 01234567 , 98765432 , aaaaaaaa, aa1123456

alguém consegue me ajudar ?

A: Pelo que conheço, não é viável detectar sequência de números com regex.
É possível detectar caracteres repetidos facilmente, como 000 ou aaa, mas uma sequência 123, 987 ou abc não.
O regex por si só, não atribui valor aos caracteres. Ele não identifica que 2 é maior que 1 ou que b é seguido de a no alfabeto.
Para fazer isso você teria que escrever todas as sequências possíveis para ele dar match em alguma delas. Como exemplo a pattern "123|12|23|321|32|21" para identificar uma sequência simples entre três números.
Para letras ou números repetidos você poderia usar um pattern que procura por ocorrências repetidas como "(\d|\w)\1+".
Nesse caso o pattern obtém uma letra ou número e logo em seguida verifica se ele se repete uma ou mais vezes.
Veja funcionando no regex101.


Q: strange behavior when using list of another class objects as class attribute in python I am having some issues with the classes below:
class book:
    def __init__(self,name=None):
        self.name=name
        return

class bookshelf:
    def __init__(self,books=[]):
        self.books=books
        return
    def add_book(self,name):
        self.books.append(
            book(name)
        )
        return

Next, I initialize list a list of bookshelves:
bookshelves = [bookshelf() for i in range(3)]

With all of them empty, both bookshelfs[0].books and bookshelfs[1].books are [].
However, after adding a book to the first bookshelf,
bookshelves[0].add_book('Book1')

all books have a book named "Book1": both bookshelves[0].books[0].name and bookshelves[1].books[0].name have the value 'Book1'.
This does not change even after I reinitialize the list of bookshelf. But if I rerun the section defining the classes, the bookshelfs will be cleared.
Any ideas how does this happen? How should I implement this part correctly? By the way, I am running Python 3.8.3 .

A: Python Mutable Default Arguments are counter-intuitive!
Python creates the list once when the method is defined not when it is called. Therefore the list obj is shared between instances. Here's A good article on the issue.
I would instead remove the default argument and check/set it in the init method.
class bookshelf:
    def __init__(self,books):
        self.books = []
        if books:
            self.books = books


Q: Dynamic content in a widget I have to make a widget from where the user will be able to add a few images and then I will show only some of them, randomly, and it will be automatically changed on page refresh. The problem is that the number of images is not known, it may be 2, it may be 5. I was thinking of using an "add more" jQuery button but I have problems with working on data from an array.
Has somebody done something like this before? If you have another idea about doing this, I'd be glad to hear of it.
Note: If you have knowledge about a widget which uses this kind of function do not hesitate to tell me, maybe I can get inspiration from there.

A: I have a little to none experience in developing a plugin or widgets, but I believe this is certainly doable in a custom WordPress theme.

*

*Output an ajax multiple file upload form in the sidebar. Link

*Handle the file uploads and save them as attachment. Link

*After you get the attachment(s) ID, save them as an array in the user's meta e.g 'sidebar_image'. Codex

*Back to the sidebar, check if current user already have the 'sidebar_image' meta.

*If she does have a value, then just create a attachment query, according to the meta value. Codex
If you want this method as a widget. The function on step 2 and 3 will be the same if you use a proper ajax method.
Hope this help.

A: This can be solved with fairly simple elements: a Shortcode and the Text Widget.
First, we enable the shortcode functionality for the widget:
// Enable shortcodes in the Text Widget
add_filter( 'widget_text', 'do_shortcode' );

Useful: Shortcodes everywhere
Then we create a shortcode that will grab images from a given post or page and display a random number of it. As we will load in random order, at each page load the images will vary.
The usage will be [random-image id="99" total="4"]. "id" is the post/page ID.  You can even leave this post in Draft state, so it doesn't show up in the site. "total" is optional and represents the number of images to show, if there are less images attached it doesn't matter, it'll show all that exist.
You can have a couple of posts for storing the images and use one widget for each. A Custom Post Type could be created and the get_posts part complexified upon it, but I'll leave that as an exercice for the reader ;)
Check the comments for further details:
// Declare our shortcode
add_shortcode( 'random-image', 'wpse_45638_random_image' );

/**
 * Shortcode
 */
function wpse_45638_random_image( $atts, $content = null )
{
    // ID not provided, bail out
    if( !isset( $atts['id'] ) )
        return;

    // Initiate variables,
    $html = '';
    $total = isset( $atts['total'] ) ? $atts['total'] : -1;
    $gallery = wpse_45638_get_gallery( $atts['id'], $total );

    // No images, bail out
    if( !$gallery )
        return;

    // Build the thumbnails
    foreach( $gallery as $image )
    {
        $html .= '

 ';
    }

    // Return contents of the shortcode
    return $html;
}

/**
 * Get images from a post
 *
 * @param int $post_id Target post/page/cpt
 * @param int $total   Number of images to retrieve
 */
function wpse_45638_get_gallery( $post_id, $total )
{
    $args = array(
        'post_type'     => 'attachment',
        'numberposts'   => $total,
        'post_parent'   => $post_id,
        'post_mime_type' => 'image',
        'orderby' => 'rand'
    );

    $attachments = get_posts( $args );
    $arr = array();

    if ($attachments)
    {
        foreach ( $attachments as $img )
        {
            // Grab our data - This can be improved
            $data = wp_get_attachment_metadata( $img->ID );
            $thumb = wp_get_attachment_thumb_url( $img->ID);loga($thumb);
            $file = wp_get_attachment_url( $img->ID);loga($file);
            $arr[] = array(
                'width' => $data['width'],
                'height' => $data['height'],
                'file' => $file,
                't_width' => $data['sizes']['thumbnail']['width'],
                't_height' => $data['sizes']['thumbnail']['height'],
                't_file' => $thumb,
            );
        }
        return $arr;
    }
    return false; // no images found
}


Q: Is there any good tool/framework to profile performance for C/C++ application I'm new to C/C++ and facing a performance issue that my program is running very slow. I want to find what's the hot spot is to reduce the overall execution time for my code.
What's the most popular and the easiest way to profile a  C/C++ application in Windows?
I've been very amazed by how easy it is to profile a .NET application using Mini Proler. Do we have any similiar library in C/C++ that gives us that high quality and reliable of result with a minimal added code?
Or is there any tool that is similiar to RedGate ANTS performance profiler  that also provider insightful information about the running code?

A: Intel's VTune or AMD's CodeAnalyst are both very good tools. On Linux, Perf or OProfile will do the same thing.

A: While you are hunting around for a profiler, run the program in the debugger IDE and try this method.
Some programmers rely on it. There's an example here of how it is used.
In that example here's what happens. A series of problems are found and removed.

*

*The first iteration saved 33% of the time. (Speedup factor 1.5)

*Of the time remaining, the second iteration saved 17%. (Speedup factor 1.2)

*Of the time remaining, the third iteration saved 13%. (Speedup factor 1.15)

*Of the time remaining, the fourth iteration saved 66%. (Speedup factor 2.95)

*Of the time remaining, the fifth iteration saved 61%. (Speedup factor 2.59)

*Of the time remaining, the sixth iteration saved 98%. (Speedup factor 45.9)
All those big-percent changes were not big percents of the original time, but they became so after other problems were removed.
The total amount of time saved from the original program was over 99.8%.
The speedup was 730 times.
Most programs that have not gone through a process like this have lots of room for speedup, but you're not likely to realize it using only a profiler because all they do is make measurements. They don't always point out to you what you need to fix, and each problem you miss keeps you from getting the really significant speedup.
To put it another way, the final speedup factor is the product of all those individual factors, and if any one of them is missed, it is not only absent from the product, but it reduces the following factors.
That's why, in performance diagnosis, "good enough" is not good enough.
You have to find every problem.


Q: Selenium Unable to select a date from date picker unable to select a date from date picker
this is the website working on https://www.phptravels.net/
when i used developer options and Ctrl + F on firebug
//div[@style='display: block; top: 390px; left: 680px;']//text()[contains(.,'15')]
i am able to find the date on the page
but when i am trying from the code i am unable to select the element
This is my code
self.driver.find_element(By.XPATH, "//div[@style='display: block; top: 390px; left: 680px;']//text()[contains(.,'"+start_date+"')]").click()

test_Flight.py:37:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
..\pages\search_flights_form.py:68: in set_start_date_pick
    self.driver.find_element(By.XPATH, "//div[@style='display: block; top: 390px; left: 680px;']//text()[contains(.,'15')]").click()
..\..\..\..\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py:976: in find_element
    return self.execute(Command.FIND_ELEMENT, {
..\..\..\..\AppData\Local\Programs\Python\Python38-32\lib\site-packages\selenium\webdriver\remote\webdriver.py:321: in execute
    self.error_handler.check_response(response)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

self = <selenium.webdriver.remote.errorhandler.ErrorHandler object at 0x052D6D18>
response = {'status': 404, 'value': '{"value":{"error":"no such element","message":"Unable to locate element: //div[@style=\'disp...ntent/shared/webdriver/Errors.jsm:395:5\\nelement.find/</<@chrome://remote/content/marionette/element.js:300:16\\n"}}'}

A: Try like below and confirm.
driver.get("https://www.phptravels.net/")

wait = WebDriverWait(driver,30)

checkin = wait.until(EC.element_to_be_clickable((By.ID,"checkin")))
checkin.click()

date = 15
select_date = wait.until(EC.element_to_be_clickable((By.XPATH,f"//div[@class='datepicker-days']//td[text()='{date}']")))
select_date.click()

Update: As per comments to select date from Flights section.
driver.get("https://www.phptravels.net/")

wait = WebDriverWait(driver,30)

flights = wait.until(EC.element_to_be_clickable((By.XPATH,"//button[@aria-controls='flights']")))
flights.click()

departure_date = wait.until(EC.element_to_be_clickable((By.XPATH,"//input[contains(@class,'depart')]")))
departure_date.click()

date = 15
select_date = wait.until(EC.element_to_be_clickable((By.XPATH,f"(//div[@class='datepicker-days'])[3]/table/tbody/tr[3]/td[text()='{date}']")))
select_date.click()


Q: PHP-FPM (7.4.2) doesn't stop gracefully? During updating, we want to stop php-fpm and wait for all running scripts to be finished before we make any file changes.
We found out that we needed to set process_control_timeout, so we placed "process_control_timeout = 36000s" in "/etc/php/7.4/fpm/pool.d/zz-00-overrides.ini" (and we restarted php-fpm).
Then we created a test script to test it out. Our test script creates a file, then 30 seconds later, it creates another file. The script:
$id = random_int(10000, 99999);
file_put_contents(__DIR__ . '/' . $id . '-start', '');
sleep(30);
file_put_contents(__DIR__ . '/' . $id . '-end', '');

When we run the script normally (browser -> nginx -> php-fpm), it creates the 1st file, 30 seconds later it creates the 2nd file.
When we run the script, wait a few seconds, and then try to stop it (run the same way as before: browser -> nginx -> php-fpm) (stopped by: "service php7.4-fpm stop"), it will create the 1st file, then the service stop command is run which only takes 2-3 seconds, then the browser says "502 Bad Gateway", and then the 2nd file is never created.
It doesn't gracefully stop. The desired outcome for us is that "service php7.4-fpm stop" waits for all the scripts to be done, and then stops, instead of it killing off any running scripts the way it is doing now in order to forcefully stop.
Are we missing something, are we doing something wrong? Is it a bug somewhere somehow? Any help would be really appreciated.

*

*Debian 10 (Linux 4.19.0-6-cloud-amd64 #1 SMP Debian 4.19.67-2+deb10u2 (2019-11-11) x86_64 GNU/Linux)

*PHP 7.4.2

*Nginx 1.14.2

A: Running kill -QUIT $(cat /run/php/php7.4-fpm.pid) does take the process_control_timeout config in account. It will cause the PHP-FPM process to stop as soon as all the scripts have finished their execution. At that point the PID will be removed. So, in order to make it work:

*

*run $(kill -QUIT $(cat /run/php/php7.4-fpm.pid))

*in a loop, check if /run/php/php7.4-fpm.pid still exists, if not, break the loop.