text:
Q: Postgres row-level security for anonymous block scripts I have a game I'm working on with Postgres as the backend. One of the features I've been struggling with is a way to allow the players to script certain aspects of the gameplay. These scripts would be stored in a table (text column), and at the end of each turn the scripts would be executed by a stored procedure.
I can select the script code out of that table and run it with a statement something like this:
do [script-code-here] language whatever-pl-language;
--haven't decided which languages to allow, might give them choice of several

The stored procedure that runs these will run the code under an appropriate postgres role locked down with just enough grants that they can only affect the tables (and columns) that they should be able to affect. But of course, other players' data will be in those same tables, so I need row level security so that they might be able to update/delete/insert their own rows without being able to cheat and modify opponents' rows.
The create policy examples in the Postgres documentation are sparse. I've been unable to find a USING clause that doesn't do a simple check of x = current_user (with current_user being the role the code runs under).
If I have a player_id column in the scripts table, and in all the other tables the scripts would be allowed to affect, is there a way to formulate a create policy statement that doesn't force me to create a new postgres role for every player (of which there might be an arbitrarily high number)? The anonymous code block could (for instance) set some variable to the player_id of the script running, except that the set statement can set custom parameters or variables. Nor can I find an unimportant one that can be repurposed and set to this value (it doesn't even look like they can be referenced in plsql).
Is there some feature or trick that would allow me to formulate create policy statements using the tables/columns I've described without creating new roles for each player? Postgres extension solutions are more than welcome.

A: You can create a C extension that introduces a new database parameter that can be set only once and will throw an error if you attempt to modify it. For that, you'd create a _PG_init function that calls DefineCustomStringVariable with an appropriate check function. Make sure that the resulting module is added to shared_preload_libraries so that the parameter is always defined.
Then you can set the parameter as soon as a player connects, and you can use the current_setting function in your policy definition to retrieve the current setting.
But I think that the whole idea is ill-conceived. I would never allow a user to run arbitrary SQL statements in my database. It would be trivial for any user to launch a denial-of-service attack against the database by either hogging a CPU or filling up the file system with random data. And unless you removed the CREATE privilege on schema public FROM PUBLIC, the attacker might also create objects and do even more harm.
SQL is too powerful that you can reasonably restrict it.


text:
Q: FreeBSD 13 PF blocking jail traffic After upgrading my FreeBSD system from 12.2 to 13.0-p3 PF is blocking all traffic to my jails.
When disabling PF everything works fine (except from being unprotected ;))
I tried to figure out what rule is blocking this traffic by setting 'block in log all', but apart from some obvious multicast stuff nothing comes up that could explain why this traffic is blocked.
Again, before everything worked perfectly fine under version 12.2.
I did find some articles about v13 now filtering over VLAN instead of lo0 but I don't use any VLANs.
In what direction should I seek further?
Update 2021-07-15:
For clarity sake: heres my pf_rules file:
set block-policy return
set optimization aggressive
set skip on { lo0, lo1, lo2, lo3, lo4, lo5 }
ext_if=hn0
ext_address="{ 192.x.x.x, 2001:981:x.x::x }"
ext_services = "{ ssh, http, https, smtp, smtps }"
tcp_services = "{ ftp, ssh, domain, ntp, www, smtp, smtps, submission, http, https,nfs}"
udp_services = "{ domain, ntp, nfs }"
icmp6_types="{ 2, 128 }" # packet too big, echo request (ping6)
icmp6_types_ext_if="{ 128, 133, 134, 135, 136, 137 }"
jail_net = "192.168.1.0/24"
jail_services = "{ mysql, http, smtp, 587, 3000 }"
table <sshguard> persist
scrub in all
nat pass on $ext_if from $jail_net to any -> $ext_address
block in log on $ext_if proto tcp from <sshguard> to any port ssh label "ssh bruteforce"
block in log all
pass in quick from <pf_whitelist> flags S/SA synproxy state
pass out on $ext_if inet6 proto icmp6 all icmp6-type echoreq keep state
pass out on $ext_if inet proto udp to port 33433:33626
pass out on $ext_if inet6 proto udp to port 33433:33626
pass in on $ext_if inet6 proto ipv6-icmp icmp6-type $icmp6_types keep state
pass in on $ext_if inet6 proto ipv6-icmp from any to { ($ext_if ), ff02::1/16 } icmp6-type $i
cmp6_types_ext_if keep state
pass in on $ext_if proto tcp from any to $ext_address port $ext_services keep state
pass in on $ext_if inet6 proto tcp from any to $ext_address port $ext_services keep state
pass out on $ext_if inet proto tcp to any port $tcp_services keep state
pass out on $ext_if inet6 proto tcp to any port $tcp_services keep state
pass out on $ext_if inet6 proto udp to any port $udp_services
pass proto udp to any port $udp_services keep state
pass in proto tcp from any to $jail_net port $jail_services keep state
pass out proto tcp from $jail_net to any port $jail_services keep state
pass inet proto icmp from any to any

This has worked for many years until FreeBSD 13

A: Quoting from TCP SYN Proxy:
| The SYN proxy will not work if PF is running on a bridge(4).
Remove the flag synproxy
pass in quick from <pf_whitelist> flags S/SA synproxy state

Try instead
pass in quick from <pf_whitelist> flags S/SA keep state

If this works you can use it for jails only and keep synproxy for others, e.g.
pass in quick from <pf_whitelist> to $jail_net flags S/SA keep state
pass in quick from <pf_whitelist> flags S/SA synproxy state

A: Apparantly this had nothing to do with PF but something with the upgrade process from version 12.2 to 13.0.
Installing version 13 on a physical server and creating a jail with some services worked fine. So it could have something to do with the upgrade on a virtual server, be it Hyper-V or something else. I still don't know as everything in settings and config looks the same (most part I copied from the upgraded virtual server where it doesn't work)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display parameter in Web API help page documentation for Response only? I've configured Web API help page documentation.
I am having below class which would be inherited in other model classes.
public class ResponseBase
{
    public string ErrorReason { get; set; }
    [IgnoreDataMember]
    public bool IsRejected { get; set; }
}

I don't want IsRejected to be serialized and available in response so I decorated it with IgnoreDataMember attribute.
Example of model class that inherits ResponseBase.
public class Reading : ResponseBase
{
    //Other properties
}

I've below method in my Web API Controller:
[HttpPost]
[ValidationResponseFilter]
[Route("")]
[ResponseType(typeof(Reading))]
public IHttpActionResult Add(List<Reading> readingList)
{
    //Logic here
}

Now for the documentation of request parameter which is list of Reading objects, it will list down all the properties of Reading along with ResponseBase class(inheritance). I want help page documentation to list down  ErrorReason as one of the parameter in Response only.
Is there any configuration I can do other than setting attribute [ApiExplorerSettings(IgnoreApi = true)] on ErrorReason? If I do that, ErrorReason will
not be available in both Request and Response Parameters. I want to display it in Response Parameters list only.

A: Generally, the best practice is to create a custom object that matches exactly what you want to accept. One of the reasons for this is security. See 'over-posting' and 'under-posting' : http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
To do this you would create a new object with only the properties you need.
public class ResponseBaseVM
    {
        public string ErrorReason { get; set; }
        /*public bool IsRejected { get; set; }*/
    }
public class ReadingVM : ResponseBaseVM
    {
        //Other properties that you only want available to user
    }

Then you would take in List of ReadingVM but the response type would still be typeof(reading)
[HttpPost]
[ValidationResponseFilter]
[Route("")]
[ResponseType(typeof(List<Reading>))] //will still display response with IsRejected
public IHttpActionResult Add(List<ReadingVM> readingListVM)
{
    //Logic here
}

--- Work Around ---
Again, I think you should follow the method above. You asked for a work around and here it is. Find your 'GenerateApiModel' method in the HelpPageConfigurationExtensions.cs class and repalce it with this:
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
    HelpPageApiModel apiModel = new HelpPageApiModel()
    {
        ApiDescription = apiDescription,
    };

    ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
    HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
    GenerateUriParameters(apiModel, modelGenerator);
    GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
    GenerateResourceDescription(apiModel, modelGenerator);
    GenerateSamples(apiModel, sampleGenerator);

    //This will remove request body parameters from your Api Help Page matching 'IsRejected'
    var isRejectedParameter = apiModel.RequestBodyParameters.SingleOrDefault(x => x.Name == "IsRejected");
    if (isRejectedParameter != null)
        apiModel.RequestBodyParameters.Remove(isRejectedParameter);

    //This will remove elements with 'IsRejected' for the Help Page sample requests
    var sampleRequests = new Dictionary<MediaTypeHeaderValue, object>();
    foreach (var kvp in apiModel.SampleRequests)
    {
        //1.) iterate through each object in SampleRequests dictionary.
        //2.) modify the json or xml to remove the "IsRejected" elements
        //3.) assign modified results to a new dictionary
        //4.) change the HelpPageApiModel. SampleRequests setter to be not private
        //5.) assign new dictionary to HelpPageApiModel.SampleRequests
        if (Equals(kvp.Key, new MediaTypeHeaderValue("application/json")))
        {
            var jObject = JObject.Parse(kvp.Value.ToString());
            jObject.Remove("IsRejected");
            sampleRequests.Add(new MediaTypeHeaderValue("application/Json"), jObject.ToString());
        }
        else if(Equals(kvp.Key, new MediaTypeHeaderValue("text/json")))
        {
            //do stuff
        }
        else if (Equals(kvp.Key, new MediaTypeHeaderValue("application/xml")))
        {
            //do stuff
        }
        else if (Equals(kvp.Key, new MediaTypeHeaderValue("text/xml")))
        {
            //do stuff
        }
        else
        {
            //form urlencoded or others
            sampleRequests.Add(kvp.Key,kvp.Value);
        }
    }
    apiModel.SampleRequests = sampleRequests;

    return apiModel;
}

Now as you can see 'IsRejected' exists in the Response, but not the Reqest.

A: I suggest you use HTTP Status Codes as a way of conveying success or failure, such as they are meant to, unless there's a specific reason you want to return the errors as a HTTP Status Code 200 (OK) instead.
The general way of dealing with such a scenario is to return 2xx-status codes when everything is ok, and 4xx or 5xx status codes when an error occurred. This way the client can clearly distinguish error situations from successful operations.
A good blog post on the subject on error handling can be found on Exception Not Found -blog, from where this good example of a controller action is taken:
[Route("CheckId/{id}")]
[HttpGet]
public IHttpActionResult CheckId(int id)
{
    if (id > 100)
    {
        var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new StringContent("We cannot use IDs greater than 100.")
        };
        throw new HttpResponseException(message);
    }
    return Ok(id);
}


text:
Q: Installing a package doesn't show in my package.json file I have a weird problem when I install a Node.js package:
npm i socket.io

It doesn't appear in my package.json file as a dependency, but it was installed and I can use it. The problem is, when someone will download it from GitHub, he/she needs to install socket.io manually instead from just npm i. How can I add it?

A: Use
npm i --save socket.io

The --save option will add the package to your dependencies.


text:
Q: Can't mount disk image I have a disk image file I'm trying to mount locally using a loop device. Using parted I can see the image has two partitions, however, I'm not able to mount the first partition and losetup thinks the second partition doesn't exist. Anyone know how I can mount the second partition?
/m/sf_VMShare ❯❯❯ sudo losetup /dev/loop0 ./imm_image-2017-05-28.img
/m/sf_VMShare ❯❯❯ sudo losetup -a
/dev/loop0: [0023]:99 (/media/sf_VMShare/imm_image-2017-05-28.img)
/m/sf_VMShare ❯❯❯ sudo parted /dev/loop0 print
Model: Loopback device (loop)
Disk /dev/loop0: 1206MB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size   Type     File system  Flags
 1      10.5MB  360MB   349MB  primary  ext4
 2      361MB   1205MB  844MB  primary  ext4

/m/sf_VMShare ❯❯❯ sudo mount -t ext4 /dev/loop0p2 /tmp/vdisk
mount: special device /dev/loop0p2 does not exist
/m/sf_VMShare ❯❯❯ sudo mount -t ext4 /dev/loop0p1 /tmp/vdisk
mount: wrong fs type, bad option, bad superblock on /dev/loop0p1,
       missing codepage or helper program, or other error
       In some cases useful info is found in syslog - try
       dmesg | tail  or so

/m/sf_VMShare ❯❯❯ mount | grep /tmp/vdisk
/m/sf_VMShare ❯❯❯
/m/sf_VMShare ❯❯❯ ls /dev/loop*
/dev/loop0    /dev/loop1  /dev/loop3  /dev/loop5  /dev/loop7
/dev/loop0p1  /dev/loop2  /dev/loop4  /dev/loop6  /dev/loop-control
/m/sf_VMShare ❯❯❯ lsblk -f
NAME      FSTYPE LABEL MOUNTPOINT
sda
├─sda1                 /
├─sda2
└─sda5                 [SWAP]
sdb
└─sdb1                 /home/foo/workspace
sr0
loop0
└─loop0p1

A: Running losetup -P will automatically detect partitions and create appropriate /dev/loop0pX devices for you. No need to perform the calculations manually.

A: How to mount a partition in a full disk image that contains a msdos partition table.
Tools:

*

*fdisk

*mount

*calculator

Get the partition layout of the image.
sudo fdisk -l -u=sectors /work/loop_test/disk_image.img
Example output:
Disk /work/loop_test/disk_image.img: 29 MB, 29629952 bytes
255 heads, 63 sectors/track, 3 cylinders, total 57871 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0009d7e5

                     Device Boot      Start         End      Blocks   Id  System
/work/loop_test/disk_image.img1       2048       18431        8192   83  Linux
/work/loop_test/disk_image.img2       18432      57343       19456    7  HPFS/NTFS/exFAT

Calculate the offset from the start of the image to the partition start. In this case the ntfs partition.
formula:
Sector size * Start = Offset
512 * 18432 = 9437184

Mount the image, passing the offset for the desired partition.
In this example the ntfs partition.
sudo mount -o loop,offset=9437184 /work/loop_test/disk_image.img /mnt/ntfs_partition


text:
Q: Array of char * I am having problems with array pointers. I've looked through Google and my attempts are futile so far.
What I would like to do is, I have a char name[256]. I will be 10 of those.
Hence, I would need to keep track of each of them by pointers.
Trying to create a pointer to them.
int main()
{
    char superman[256] = "superman";
    char batman[256] = "batman";
    char catman[256] = "catman";
    char *names[10];
    names[0] = superman;
    names[1] = batman;
    system("pause");
    return 0;
}

How do I actually traverse an array of pointers?

A: names[0] is a char* to whatever you stored in names[0] (which in this case is a pointer to the first element in your superman array) thus your guess at e.g cout << names[0] << endl;is correct.
If you want to traverse that array, you need to know when to stop so you're not traversing pointers you havn't yet initialized- if you know you have initialized 2 of those pointers, you could do e.g.
for(int i = 0; i < 2 ; i++) {
  std::cout << names[i] << std::endl;
}

As an alternative, place a NULL pointer after the last element you have initialized(make sure there's room for that NULL pointer) e.g.
names[2] = NULL;
for(int i = 0; names[i] != NULL ; i++) {
  std::cout << names[i] << std::endl;
}

A: why not use strings and a Vector of strings to store the names?
smpl:
#include <string>
#include <iostream>
#include <Vector>

//using namespace std;

int main(void) {
    std::string superman = "superman";
    std::string batman = "batman";
    std::vector<std::string> names;
    names.push_back(superman);
    names.push_back(batman);
    for (unsigned int i = 0; i < names.size(); ++i) {
        std::cout << names[i] << std::endl;
    }
    char c; std::cin >> c;
}

A: char *names[] = { "superman", "batman", "whatever", NULL };

...
for (int i = 0; names[i] != NULL; i++)
    printf("%s\n", names[i]);

He might not want to use a vector because he might be using C, not C++.
edit: I see he tagged it C++ though.

A: Using arbitrary fixed length arrays to manipulate strings is a complete no no. In my company, this code would be illegal, period.
This practice is exactly the cause of most security breaches and it's what makes C/C++ (that uses this type of code) notoriously unsecure.
I highly recommend the C++ solution from "Oops".

A: First try using std::string, this will relieve you of memory allocation and deallocation issues.
Second, use std::vector<string> which dynamically expands as needed.
If you must use char *, you will need an array of pointers to char *.
This is declared as:
char * array_of_C_strings[10];  // Define an array of 10 pointers to char *.
If the strings are fixed length:
char array_of_fixed_length_C_strings[10][256];  // Array of 10 C-Strings that are max. size 256.
Assignment:
char hello[32];
strcpy(hello, "Hello");
array_of_C_Strings[0] = hello;  // Note: only pointers are copied
strcpy(array_of_fixed_length_C_Strings[2], hello);  // Copy actual content of string.

With std::string and std::vector<std::string>:
std::string hello = "hello";
std::vector<std::string> string_container;
string_container.push_back(hello);
string_container.push_back("world!");
std::cout << string_container[0]
          << ' '
          << string_container[1]
          << "\n";

The example using std::string and std::vector looks simpler than an array of char *, but that is my opinion, YMMV.


text:
Q: download html web page or scrape text from it I am struggling to download full html code from below page. I was using URLDownloadToFileA and MSXML2.XMLHTTP60 methods and none of them downloads full code. Part of the webpage is missing - table on the bottom with "DEBTI...." in not included in the code. My aim is to get these "DEBTI..." strings and I want to avoid selenium if possible. None of below codes work for me, but when I just ctrl+s (save) page from the browser everything is correctly mentioned in the code. Any suggestions? Thanks!
Sub Get_Data()

Dim xmlhttp As New MSXML2.XMLHTTP60, myurl As String
myurl = "https://ec.europa.eu/taxation_customs/dds2/ebti/ebti_consultation.jsp?Lang=en&Lang=en&refcountry=&reference=&valstartdate1=&valstartdate=&valstartdateto1=&valstartdateto=&valenddate1=&valenddate=&valenddateto1=&valenddateto=&suppldate1=&suppldate=&nomenc=2309&nomencto=&keywordsearch1=&keywordsearch=&specialkeyword=&keywordmatchrule=OR&excludekeywordsearch1=&excludekeywordsearch=&excludespecialkeyword=&descript=&orderby=0&Expand=true&offset=1&viewVal=Thumbnail&isVisitedRef=false&allRecords=0&showProgressBar=true" 'replace with your URL
xmlhttp.Open "GET", myurl, False
xmlhttp.Send

Open "C:\Desktop\test.txt" For Output As #1
Print #1, (xmlhttp.responseText)
Close #1

End Sub

Private Declare PtrSafe Function URLDownloadToFile Lib "urlmon" _
    Alias "URLDownloadToFileA" (ByVal pCaller As Long, ByVal szURL As String, _
    ByVal szFileName As String, ByVal dwReserved As Long, ByVal lpfnCB As Long) As Long

Function DownloadFile(URL As String, LocalFilename As String) As Boolean
    Dim lngRetVal As Long
    lngRetVal = URLDownloadToFile(0, URL, LocalFilename, 0, 0)
    If lngRetVal = 0 Then DownloadFile = True
End Function

Sub test()

    DownloadFile "https://ec.europa.eu/taxation_customs/dds2/ebti/ebti_consultation.jsp?Lang=en&Lang=en&refcountry=&reference=&valstartdate1=&valstartdate=&valstartdateto1=&valstartdateto=&valenddate1=&valenddate=&valenddateto1=&valenddateto=&suppldate1=&suppldate=&nomenc=8418&nomencto=&keywordsearch1=&keywordsearch=&specialkeyword=&keywordmatchrule=OR&excludekeywordsearch1=&excludekeywordsearch=&excludespecialkeyword=&descript=&orderby=0&Expand=true&offset=1&viewVal=List&isVisitedRef=false&allRecords=0&showProgressBar=true", "C:\Desktop\abc.html"

End Sub

web:
https://ec.europa.eu/taxation_customs/dds2/ebti/ebti_consultation.jsp?Lang=en&Lang=en&refcountry=&reference=&valstartdate1=&valstartdate=&valstartdateto1=&valstartdateto=&valenddate1=&valenddate=&valenddateto1=&valenddateto=&suppldate1=&suppldate=&nomenc=8418&nomencto=&keywordsearch1=&keywordsearch=&specialkeyword=&keywordmatchrule=OR&excludekeywordsearch1=&excludekeywordsearch=&excludespecialkeyword=&descript=&orderby=0&Expand=true&offset=1&viewVal=List&isVisitedRef=false&allRecords=0&showProgressBar=true


text:
Q: Redirecting back to app after launching UIApplication.shared.open I am trying to redirect to an app after launching a browser window using UIApplication.shared.open.
My code looks like this:
    let url = URL(string: "https://example.com/endpoint")!

    UIApplication.shared.open(url, options: [:], completionHandler: { (success) in

    })

I need to launch a browser window to generate a user fingerprint that will be the same fingerprint as the browser that the user got sent to the App Store with. However once the browser window opens and this fingerprint is generated, I no longer need the window.
Is there a way to really quickly open a window to generate this fingerprint and then close it back and hand control back to the app?
The fingerprint is being generated on the server end - all I need to do is make sure that the same browser that the user was sent to the App Store with is the same browser opened now. The default browser seems like a "good enough" situation for now.

A: Have you looked into using SFSafariViewController?
It would allow you to present a browser within the app in which at a later point you can dismiss as it's an instance of a UIViewController.
Alternatively you can use URL schemes or universal links to redirect back into the app after a fingerprint is generated i.e. https://stackoverflow.com/a/25883274/4698501


text:
Q: How to change authenticate method on IIS 7? I've got an error which tells me unauthorized. How and where to change that webserver allows anonymous (public) access?
HTTP Error 401.2 - Unauthorized
401.2 - Logon failed due to server configuration.
Something has happened on my local machine when I made the latest update for IIS, but now I'm not sure what has happened.

A: Note the following methods here:
http://support.microsoft.com/kb/942043

A: Select your website on the tree left hand side inside IIS Manager.
Double click on Authentication section from the menu (Authentication section is under the IIS caregory)
Enable Anonymous Auth. there as follows :

You can bind a user to this app by Editing the Anonymous Auth. Section. this will gives you box like this :

This should be set to IUSR by default.


text:
Q: Possible to run Google Standard Managed VM Locally with Docker for Development? Is it possible to run a Google Standard Managed VM for Java locally for development purposes? I am asking cause dev_appserver.py, mvn gcloud:run or gcloud preview app run are good for a simple hello world application, but anything bigger than that doesn't work... (single threaded, timeout, etc...).

A: I mentioned this above, but you're looking for AppStart:
https://github.com/GoogleCloudPlatform/appstart


text:
Q: Relationship between Product of $L^p$ spaces an product measures Let $(X,\Sigma,\mu)$ and $(Y,\Gamma,\nu)$ be $\sigma$-finite measure spaces.  Is there a relationship between $L^p_{\mu}(\Sigma)\times L^p_{\nu}(\Gamma)$, equipped with the product of their $L^p$-topologies, and the space $L^p_{\mu\otimes \nu}(\Sigma \otimes \Gamma)$?
More generally, let $(X_i,\Sigma_i,\mu_i)$ be a countably infinite familly of $\sigma$-finite measure spaces, then is
$$
\prod_{i=1}^{\infty} L_{\mu}^p(\Sigma_i) \mbox{ dense in } L^p_{\bigotimes_{i=1}^{\infty} \mu_i}\left(\bigotimes_{i=1}^{\infty}\Sigma_i\right)?
$$

Ideas and Update:
Initially, my intuition was (as noted in the comment below) to pass through the completed injective tensor product $L_{\mu}^p(\Sigma)\otimes_{\epsilon} L^p_{\nu}(\Gamma)$.
Though now I doubt that works since according to this post and some results of Grothendieck, if $p=1$ then $L_{\mu}^p(\Sigma)\otimes_{\epsilon} L^p_{\nu}(\Gamma)\cong L_{\mu}^p(X;L_{\nu}^p(\Gamma))$ (the Pettis-Gel'fand integrable functions).


text:
Q: Need to convert NSData to NSArray I am pulling down a plist from a URL using an NSURLConnection, which returns an
NSData object. I would like to convert this to an NSArray. Can anyone help me?
I am refactoring a method that currently does a synchronous request to the URL,
using arrayWithContentsOfURL: to get the NSArray.
Thanks!!

A: Use +[NSPropertyListSerialization dataWithPropertyList:format:options:error:] to convert the data, then check if the result -isKindOfClass:[NSArray class].

A: Use NSKeyedArchiver for archiving object to data.
NSKeyedUnarchiver for unarchiving object from data:
NSArray *object = [NSKeyedUnarchiver unarchiveObjectWithFile:self.receivedData];


text:
Q: Count & print the checked inputs with AngularJS I used ng-repeat to print the list of input checkbox. How do I count and print the number of checked checkboxes?
JavaScript
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.lists = [{'id':'1', 'name':'list 1'},
                    {'id':'2', 'name':'list 2'},
          {'id':'3', 'name':'Macbook Pro'},
          {'id':'4', 'name':'Dell Optiplex 755'},
          {'id':'5', 'name':'Google Nexus S'}
          ];
});

HTML

  <input type="text" ng-model="fil.name" />

        <input type="checkbox" name="list_id[]" value="{{list.id}}" />
           {{list.name}}

http://plnkr.co/edit/4swnCWen370VhTuca0u2?p=preview

A: JS:
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  $scope.lists = [
    {'id':'1', 'name':'list 1', checked: true},
    {'id':'2', 'name':'list 2'},
    {'id':'3', 'name':'Macbook Pro'},
    {'id':'4', 'name':'Dell Optiplex 755'},
    {'id':'5', 'name':'Google Nexus S'}
  ];

  $scope.$watch('lists', function(lists){
    $scope.count = 0;
    angular.forEach(lists, function(list){
      if(list.checked){
        $scope.count += 1;
      }
    })
  }, true);

});

VIEW:

    <input type="text" ng-model="fil.name" />

          <input type="checkbox" name="list_id[]" ng-model="list.checked" value="{{list.id}}" />
             {{list.name}}

  Count: {{count}}

Plnkr


text:
Q: User opt-out with gtag.js We're looking to implement the option for our website visitors to disable tracking.
I've read the Google Analytics opt-out dev guide but I'm still not totally clear on how to do this.
Is it sufficient to just trigger window['ga-disable-GA_TRACKING_ID'] = true; when a button is clicked?
Will Google Analytics remember the setting for this user, or is it on a per-visit basis?
Can the user re-enable tracking if I have a second button that sets it to false?

A: Paste the following into the head tag before the Analytics code (replacing the UA with your own UA)

And use this to trigger it:
Click here to opt-out of Google Analytics

A: Thanks for the reply!
Since I replied to your post, I too came up with a solution but have yet to find a way of removing the cookie if a user chooses to opt out. While data doesn't get sent back to Google, it would just be nice to remove the cookie for completion. Here's what I came up with.

And this is triggered by
<form class="form-inline">
<button value="optin" onClick="optIn();" class="btn btn-primary mb-2">Opt In</button>

<button value="optout" onClick="optOut();" class="btn btn-primary mb-2">Opt Out</button>
</form>

So what this is doing is setting window['ga-disable-TRACKING-ID'] to either true or false, depending on the visitors response, which gets stored in SessionStorage. Hope this helps anyone as well as the solution above.

A: GTag Opt In is a tool that does it for you plus allows you to have cookies disabled by default and enable them later, disable again, enable again, and so on.
Disable cookies

--

At the point where GA is implemented, this needs to be updated by just importing the gtag.js script and removing the GA initialisation.
Enable GTag when user accepts cookies
GTag Opt In is a tool that enable and disable GA when user accepts/rejects cookies.

ACCEPT
REJECT

First, library is loaded.
Second, the GA tracking ID is registered.
Third, the optIn and optOut functions are bind to user actions' accept/reject.
You can read more about it on How To Implement Google Analytics With Opt In.


text:
Q: Open PDF as a web page I would like to know if there is a way to transform a PDF document in a web page, similar to what Office Web Apps do for Office documents.
Thanks

A: After a quick google, found this, might be of some help: http://www.softwaregeek.com/download/pdfapps_convert_pdf_to_html.html
Previous post, disregard but I do point out some slightly related other tools out there:
I know Bamboo do something along these lines here:
http://store.bamboosolutions.com/ps-16-5-office-to-pdf-conversion-business-component.aspx
The guys at Muhimbi also do some PDF stuff, but I think they only convert to PDF (could be wrong though, have a look: http://www.muhimbi.com) - a user on here is from Muhimbi so can give more advice if they do do such a product.

A: The new office web apps are capable of that: http://melcher.it/2013/05/install-office-web-apps-2013-for-sharepoint-2013-with-pdf-preview/

A: Go to Web application settings and change the settings of Browser file handling category

(source: shareesblog.com)
Finally go to Library  advance settings and Choose File open in the Browser option.
2) Another one is using page viewer web part you can achieve the PDF open in browser.

A: I know a very good solution,the site link:allowing PDFs to Open in a Browser in SharePoint 2010, the Right Way.Maybe helpful to you!


text:
Q: PGR_CreateTopology maintain Source and Target ID's Is there a way to set the 'source' and 'target' manually and not have it overridden in PGR_CreateTopology()?
I have a predefined node ID's (INODE, JNODE) in my table which is the same to a other tables in my database that I want to maintain for simplicity and consistency. This is happening:

GID  | INODE  | JNODE  | SOURCE  | TARGET
---- | ------ | ------ | ------- | ------
1    | 25     | 6      | 1       | 2

and I want this:

GID | INODE | JNODE | SOURCE | TARGET
--- | ----- | ----- | -----  | ------
1   | 25    | 6     | 25     | 6

A: pgr_createTopology() will always recreate the topology for the whole network. So if you want to preserve source and target, you shouldn't run this function.
It's no problem to use data, that already has network topology attributes (you may want to renumber it, because lower numbers will be better for performance). If you want to fill in the values manually, then you can do this of course, or you can write your custom function (or own tool) to do this.


text:
Q: Can I pass a variable from a Jekyll template to an include then render data with that variable? In foo.html (a post), I have the following:
{% assign table_name="application" %}
{% include table.html %}

This assignment appears to work fine in table.html
{% assign tableName = table_name %}

table name is: {{ tableName }}
 # renders "table name is: application"

Now, I'm trying to sort through an array of data that I have defined in config.yml by doing the following:
{%  for header in site.table.tableName.headers %}
{{ header }}
{% endfor %}

This gives me no output whatsoever.
If I change the for statement to include the variable's content, not the variable, it works fine.
{%  for header in site.table.application.headers %}

This leads me to believe that it's not a problem with my array but that it's either a shortcoming of Jekyll, a bug in Jekyll, or I'm not accurately constructing my statements.
Any idea how I could make this work?

A: Looks like this can be done. I had to think about it more programmatically. What seems to be happening is that Jekyll was expecting an object and I was feeding it a string.
{% assign tableName = "aStringName" %}
{% include table.html %}

so,
# in _includes/table.html
{%  for header in site.table.tableName.headers %}

was being interpreted as
{%  for header in site.table."aStringName".headers %}

When I switched to bracket notation for the object, it was perfect.
Final result:
{% for header in site.table[tableName].headers %}

or, as Jekyll sees it,
{% for header in site.table['aStringName'].headers %}


text:
Q: 14.04 to 16.04 *KILLED* mysql Definition:  trust - Something that the Ubuntu LTS packagers have lost from me.
I scrupulously maintained my 14.04 LTS web server machine.  It only had four primary functions (ssh, ftp, http, and mysql (for use by web pages)).  Before I started my release upgrade from 14.04 to 16.04, I made sure that both
 sudo apt-get update
 sudo apt-get upgrade
 sudo apt-get dist-upgrade

to be absolutely certain I had the latest 14.04 packages before trying to upgrade the release.  Once that was done, and the system was rebooted (and ran the above commands again, to be sure they didn't see anything new), just to be safe, I ran 'sudo do-release-upgrade -d' to go from 14.04 to 16.04.
Everything we quite smoothly of the previous two systems upgraded the same way, but the web server upgrade hung during the mysql part and it appears to have destroyed any ability I have to run mysql on the system.  Period.
From what I've read, people are STRONGLY recommended to upgrade mysql 5.5->5.6->5.7, because jumping directly from 5.5 to 5.7 can cause some table compatibility problems.  Unfortunately, my (fully up-to-date, remember) web server was still running mysql-5.5.
I have copies of /var/lib/mysql that I captured while do-release-upgrade was hung, but mysql-5.7 AND mysql-5.6 both refuse to use them.  It appears to be impossible to install mysql-5.5 on Ubuntu 16.04 in order to manually step through the releases. I tried getting the packages from the mysql web site, but I can only find mysql-server there, not -client, -common or anything else.
So, the 14.04 to 16.04 upgrade appears to have destroyed my database.  Yes, I know, not having a current backup is my fault, but after two flawless upgrades, and under a deadline (that has evaporated, since the database seems to be gone for good, now) I was too comfortable -- I had trust in the people who built the upgrade.  I know I should check in advance for anything that might break but, honestly, I thought that was the packager's job.  Saying the customer should check everything is like saying a car buys should have the car disassembled and every part checked for flaws prior to purchase -- it ain't gonna happen.
If there is any way to return to mysql 5.5 on Ubuntu 16.04 so that I can run through the CORRECT/RECOMMENDED (by mysql) upgrade procedure, please let me know.  If not, does anyone know of a good primal scream therapy group in Central Florida?
UPDATE:  I've managed to get the database in good working order again by building a virtual 14.04 server and repairing/rebuilding the database files on it.  I successfully upgraded the virtual 14.04's mysql from 5.5 to 5.6.  Next, I need to learn what I must do in order to be sure the 5.6 to 5.7 upgrade works.
UPDATE 2:  Despite the scoldings, I've managed to get my repaired database to work under mysql 5.6 on the upgraded system.  Now I'm getting errors because PHP support for mysql is not installed.  They may be baby steps, but it is progress!
Update 3:  SUCCESS!  I reinstall all of the php7 /mysql packages and made sure my web app was using the mysqli database type and, voila!  I think I'll stay at mysql 5.6 for a while, though.  Until I'm a bit more comfortable with the upgrade path to 5.7.x.  Hopefully, this may provide a cautionary tale to others like me -- but if they're too much like me, then they won't see this until it is too late.

A: This happens because upgrading from 14.04 to 16.04 causes an unsupported mysql upgrade (5.5 -> 5.7), which is not a supported upgrade path as documented by mysql. The easiest way around this is to upgrade mysql to 5.6 whilst still under 14.04. You achieve this by first (of course!) dumping all your databases;
mysqldump --lock-all-tables -u root -p --all-databases > backup.sql

then upgrading to mysql 5.6;
apt-get install mysql-server-5.6 mysql-client-5.6 mysql-server-core-5.6 mysql-client-core-5.6

This way, all your databases are upgraded in place and (on my machines so far) entirely safely and transparently to 5.6. The only issue after the upgrade may be TIMESTAMP entries. Now, after the do-release-upgrade, mysql is still left at 5.6 and the issues surrounding the non-supported upgrade from 5.5 directly to 5.7 during the release upgrade never even surface.


text:
Q: VBA Reference Named Range ActiveSheet How do I reference a named range on the ActiveSheet using VBA? I have several worksheets, each with a named range that uses the same title. None of the below work:
ActiveSheet.NamedRange
ActiveSheet!NamedRange

A: You need to use:
ActiveSheet.Range("myNamedRange")

or just
Range("myNamedRange")

it's the same for ActiveSheet
If you need to get named range from another worksheet, use following code:
Worksheets("Sheet1").Range("myNamedRange")

A: You may also reference it by bracket, example:
[my_table]

or
ActiveSheet.[my_table]

and you avoid using the quotation marks.


text:
Q: Parallel R on a Windows cluster I've got a Windows HPC Server running with some nodes in the backend. I would like to run Parallel R using multiple nodes from the backend. I think Parallel R might be using SNOW on Windows, but not too sure about it. My question is, do I need to install R also on the backend nodes?
Say I want to use two nodes, 32 cores per node:
cl <- makeCluster(c(rep("COMP01",32),rep("COMP02",32)),type="SOCK")

Right now, it just hangs.
What else do I need to do?  Do the backend nodes need some kind of sshd running to be able to communicate each other?

A: Setting up snow on a Windows cluster is rather difficult.  Each of the machines needs to have R and snow installed, but that's the easy part.  To start a SOCK cluster, you would need an sshd daemon running on each of the worker machines, but you can still run into troubles, so I wouldn't recommend it unless you're good at debugging and Windows system administration.
I think your best option on a Windows cluster is to use MPI. I don't have any experience with MPI on Windows myself, but I've heard of people having success with the MPICH and DeinoMPI MPI distributions for Windows.  Once MPI is installed on your cluster, you also need to install the Rmpi package from source on each of your worker machines. You would then create the cluster object using the makeMPIcluster function.  It's a lot of work, but I think it's more likely to eventually work than trying to use a SOCK cluster due to the problems with ssh/sshd on Windows.
If you're desperate to run a parallel job once or twice on a Windows cluster, you could try using manual mode.  It allows you to create a SOCK cluster without ssh:
workers <- c(rep("COMP01",32), rep("COMP02",32))
cl <- makeSOCKluster(workers, manual=TRUE)

The makeSOCKcluster function will prompt you to start each one of the workers, displaying the command to use for each. You have to manually open a command window on the specified machine and execute the specified command. It can be extremely tedious, particularly with many workers, but at least it's not complicated or tricky.  It can also be very useful for debugging in combination with the outfile='' option.


text:
Q: Customer Portal (Experience) User Can Upload Files to Case yet Cannot View Files Uploaded to Case by Salesforce User Our Customer Portal (Experience) users are able to upload files to a case, yet they cannot view files uploaded to a case by an internal Salesforce user.
I have enabled the 'Let customer users access notes and attachments' checkbox in Setup > Digital Experience > Settings.
However, the Customer Portal (Experience) user is only able to upload files to the case, but not able to see the files uploaded to the case by (for example case owner).
Any advice would be greatly appreciated.

A: This is because the files owned by internal users are being marked as private.
You can read more about this via below article link
https://help.salesforce.com/s/articleView?id=sf.collab_files_make_private.htm&type=5
Also note that Files is a different than Notes and Attachments. So the settings that you have got is not going to work.

To view a file on a record, the user requires access to the record. The file visibility on the record must be set to allow site users.

The users can explicitly share access to the various users in such case using share button in the files page.
More on how File sharing and visibility works is shared in below documentation
https://help.salesforce.com/s/articleView?id=sf.networks_files_visibility_and_sharing.htm&type=5


text:
Q: Stored procedure with optional OFFSET query I am trying to write a stored procedure to get data and stored procedure is as below -
 ALTER PROCEDURE SPProfileScholarshipReports
@scholarshipGroupCode nvarchar(50),
@statuses nvarchar(350),
@studentSearch nvarchar(100),
@fromDateString nvarchar(50),
@toDateString nvarchar(50),
@studentTypeFilter nvarchar(50),
@offsetFrom INT,
@offsetTo INT,
@sortColumn nvarchar(50),
@sortOrder nvarchar(10),
@isExportToExcel BIT
AS
 Begin
    SET NOCOUNT ON;
    -- variable declaration
 declare @Separator varchar(1)= ','
 DECLARE @XML XML
 declare @studentType varchar(20)= null
 IF(@studentSearch = '')
    set @studentSearch = null
 IF(@studentTypeFilter = 'new')
    set @studentType = 'false'
 else if(@studentTypeFilter = 'continuing')
    set @studentType = 'true'
 else set @studentType = null

 if(@sortOrder = '' or @sortOrder is null)
    set @sortOrder = ' DESC '
 else if(@sortOrder = 'true')
    set @sortOrder = 'ASC'
 else
    set @sortOrder = 'DESC'
    -- accept comma separated parameters and convert them to use for in
clause condition
   declare @tPsListViewStatus TABLE (val nvarchar(3600))
    IF(@statuses is not null and @statuses<>'' and @statuses like '%,%')
      BEGIN
        set @statuses = replace(replace(replace(replace(@statuses,' , ',','),', ',','),' ,',','),' ','')
    SET @XML = CAST( ('' + REPLACE(@statuses, @Separator, '') + '') AS XML)
    INSERT INTO @tPsListViewStatus
      select    t.i.value('.', 'VARCHAR(2000)')
      FROM  @XML.nodes('i') AS t(i)
      WHERE t.i.value('.', 'VARCHAR(2000)') <> ''
  END
            select * from
                (
                    select
                        (nm.LastName+' ' + nm.FirstName) as studentName,
                        pi.value,
                        ps.isContinuing,
                        sc.name as scholarshipName,
                        ps.status,
                        ps.CreatedDate,
                        ps.summary,
                        ps.effectiveDate,
                        ps.expiryDate,
                        sc.id as scholarshipId,
                        (SELECT STUFF((SELECT ',' + t.code FROM Academic_Term t WHERE t.effectiveDate >= ps.effectiveDate
                        and t.expiryDate <= ps.expiryDate and t.active = 'true' and t.code not like '%.%' and t.code not like '%COFA%'
                        and t.code not like '%NUR%' order BY t.code asc FOR XML PATH('')),1,1,'')) as code,
                        (SELECT SUM( convert( decimal( 10, 2 ), AmountAwarded )) as athleticAmount FROM profile_scholarship
                        WHERE (Status IN(select * from @tPsListViewStatus)) and id= ps.id) AS PS_amountAwarded,
                        (SELECT DISTINCT(fs1.code)
                         FROM profile_scholarship_term pst LEFT OUTER JOIN fund_source_academic_term fsat ON pst.FundSourceAcademicTermId=fsat.Id
                         LEFT OUTER JOIN fund_source fs1 ON fsat.FundSourceId=fs1.Id WHERE ps.Id = pst.ProfileScholarshipId) as fundSourceCode,
                        ps.studentProgramId,
                        ps.id as psId,
                        ROW_NUMBER() OVER(
                            PARTITION by ps.scholarshipId,
                            ps.profileId,
                            ps.status
                        ORDER BY
                            ps.EffectiveDate desc,
                            ps.ExpiryDate desc,
                            ps.CreatedDate desc
                        ) AS RowNumber,
                        ps.profileId,
                        ps.FAStudentAcademicYearId
                    from
                        profile_scholarship ps
                    INNER JOIN scholarship sc on
                        ps.ScholarshipId = sc.id
                    INNER JOIN dbo.scholarship_sub_group ssg on
                        sc.ScholarshipSubGroupId = ssg.Id
                    INNER JOIN dbo.scholarship_group sg on
                        ssg.ScholarshipGroupId = sg.Id
                    INNER JOIN name nm on
                        ps.ProfileId = nm.profileId
                    INNER JOIN dbo.profile_identity pi on
                        ps.ProfileId = pi.ProfileId
                    where
                        sg.code = @scholarshipGroupCode and ps.SystemIdentified = 'SIS'
                        and (ps.Status  IN(select * from @tPsListViewStatus))
                        AND((ps.status = 'DELETED' AND ps.summary like '%CVUE_DELETE%') OR (ps.status != 'DELETED'))
                        and pi.type = 'STUDENT_NUMBER'
                        and(ps.isContinuing IN(@studentType) or ISNULL(@studentType,'')= '')
                        and ps.CreatedDate BETWEEN @fromDateString AND @toDateString
                        ) as resultList
            where resultList.rowNumber = 1 and (ISNULL(@studentSearch,'')= ''  or resultList.studentName like '%' + @studentSearch + '%'
                    or resultList.value like '%' + @studentSearch + '%')
            order by
            case
                when @sortOrder <> 'DESC' then ''
                when @sortColumn = 'modified' then resultList.CreatedDate end DESC,
            case
                when @sortOrder <> 'ASC' then ''
                when @sortColumn = 'modified' then resultList.CreatedDate end ASC,
            case
                when @sortColumn = '' then resultList.CreatedDate end
            DESC
            OFFSET @offsetFrom ROWS FETCH NEXT @offsetTo ROWS ONLY
END

In this query I want to remove "OFFSET @offsetFrom ROWS FETCH NEXT @offsetTo ROWS ONLY" if @isExportToExcel is true. the value of @isExportToExcel is being passed from java code. I tried with below CASE statement but it is not working
Case
  when @isExportToExcel = 0 then 'OFFSET @offsetFrom ROWS FETCH NEXT @offsetTo ROWS ONLY' END

But this is not working and I am always getting completed data and pagination is not working with this

A: You can't use an inline CASE expression to determine if there will be an OFFSET or not.
I can think of three ways you can do this:
One is to write your entire query with dynamic sql.
The other is to split the logic:
IF @isExportToExcel = 0
  --Do the query with the OFFSET
ELSE
  --Do the query without OFFSET

The third is to re-populate the parameters based on the boolean:
IF @isExportToExcel = 1
  BEGIN
  SET @offsetFrom = 0;
  SET @offsetTo = {Query that gets the total count of rows that will be returned by the main query}
  END

--then execute your main query as is.


text:
Q: Create only some module in a maven profile doesn't work by  tag I have a Maven multi module project. in a specific profile named "release" I defined only some modules.
 <modules>
        <module>media</module>
        <module>persistence</module>
        <module>web</module>
</modules>

but when I build and active release profile, all module target will create. why ? and how to solve it ?

A: It works for me:
    <!--<modules>
        <module>dao</module>
        <module>web</module>
    </modules>-->

    <profiles>
        <profile>
            <id>CustomProfile</id>
            <modules>
                <module>dao</module>
            </modules>
        </profile>
        <profile>
            <id>default</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <modules>
                <module>dao</module>
                <module>web</module>
            </modules>
        </profile>
    </profiles>

[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] dao ................................................ SUCCESS [  1.213 s]
[INFO] MyCustomProject .................................... SUCCESS [  0.016 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1.394 s
[INFO] Finished at: 2017-12-31T13:42:44+03:00
[INFO] Final Memory: 11M/245M
[INFO] ------------------------------------------------------------------------

I use Apache Maven 3.5.2


text:
Q: How to toggle microphone off/on? On macos (Monterey/version 12) how can I toggle the microphone off/on (mute/unmute)? If there's no control for this, is there a way to script it for macos specifically to achieve the desired effect of quickly toggling the microphone?
Various apps use the microphone (eg web/webrtc calling, desktop calling/meeting apps, etc) and don't actually mute when I select that option, they simply turn off the audio stream. How can I control my own microphone from the OS instead of the various oddities and quirks of app developers (regardless of whether it's in browser or otherwise)?
Thanks.

A: The Sound preferences control panel provides the control for muting and adjusting the microphone in the [Input] tab. When adjusting the volume slider to the far left/down it results in the calling apps warning me my microphone is muted, as expected.
For convenience I searched in the App Store for "mute mic" and found MuteKey which when open allows toggling the microphone off and on (and has settings for opening on login).
Related to this a scripted solution is mentioned in Saaru's comment above which is super helpful and I might try as well. However that scripted solution aiming to solve a slightly different, related problem.


text:
Q: How to show the user information? I am a new ASP.NET developer. I am working on a simple project and I want to show the user information from the user table in the UserProfile page.
By the way, I am not using ASP.NET membership.
My Query for showing the information is correct and it works fine but the problem how to give it the Username of the user to retrieve his information directly in the page.
The query is:
SELECT     dbo.employee.Name, dbo.employee.Username, dbo.employee.JobTitle, dbo.employee.BadgeNo, dbo.Divisions.DivisionName, dbo.Roles.RoleName,
                      dbo.employee.EmpOrgType
FROM         dbo.Divisions INNER JOIN
                      dbo.employee ON dbo.Divisions.SapCode = dbo.employee.DivisionCode INNER JOIN
                      dbo.UserRole ON dbo.employee.Username = dbo.UserRole.Username INNER JOIN
                      dbo.Roles ON dbo.UserRole.RoleID = dbo.Roles.RoleID
WHERE     (dbo.employee.Username = @Username)

I don't know if I should make the username a session or querystring or whatever. Could you please help me with this issue?
Also, could you please provide me with useful resources to get simple information and learn more about ASP.NET? I am using msdn website but it is very difficult to understand.

A: If you want to directly retrieve the information to your page you should declare variable to retrieve the user identity and others informations if you need it. So I think you can post your ASPX code so that I can help you.

A: You can store it in diffirent ways.
How to: Pass Values Between ASP.NET Web Pages
And you can learn more on ASP.net here:
ASP.NET

A: I think the best way will be storing the Username in session and retriving the name from the session to show the user's profile details.

A: For your user to get to his profile page he needs to be logged in. So if you made your own login system one way to keep track of the user is to store his username/password in session. Then when you query you can get the correct employee by accessing the session variable.
With the membership system already being built in i'm not sure why you rolled your own.

A: That depends on your authentication mechanism.
If you are using Forms based authentication, in the login page after you authenticate the user, add the username to a session variable, then pass it on to the stored proc.
If you are relying on windows based authentication. System.Threading.Thread.CurrentPrincipal.Identity.Name will give the username.


text:
Q: Asp.net core 2.0 middleware - accessing config settings In a asp.net core web api middleware, is it possible to access the configuration inside the middleware?  Can someone guide me how this is done?

A: In a middle-ware you can access settings. To achieve this, you need to get IOptions<AppSettings> in the middle-ware constructor. See following sample.
public static class HelloWorldMiddlewareExtensions
{
    public static IApplicationBuilder UseHelloWorld(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<HelloWorldMiddleware>();
    }
}

public class HelloWorldMiddleware
{
    private readonly RequestDelegate _next;
    private readonly AppSettings _settings;

    public HelloWorldMiddleware(
        RequestDelegate next,
        IOptions<AppSettings> options)
    {
        _next = next;
        _settings = options.Value;
    }

    public async Task Invoke(HttpContext context)
    {
        await context.Response.WriteAsync($"PropA: {_settings.PropA}");
    }
}

public class AppSettings
{
    public string PropA { get; set; }
}

For more information see here.


text:
Q: How to allow to run one job, but do not allow to run another job? Is it possible in Hudson to allow some people to run one job, but do not allow to run another job?
As far as I can see it is possible only to allow to run ALL jobs.

A: Hudson's Matrix-based Security and Project-based Matrix Authorization allow fine-grained authorization control. I haven't set up the Project-based Authorization on my site, but on the System Configuration screen it says you can set up a project-specific ACL on the job configuration page.


text:
Q: "God reminded them that if they turned away from God, they would be cursed." As for the use of 'if', especially when I'm not talking about 'unreal' situations, I'm confused about what is the correct way to use it when I talk about something that happened in the past. For example,

*

*God reminded them that if they turned away from God, they would be cursed.

(but it may sound like, they will hardly ever turn away from God, right…?)

*

*God reminded them that if they have turned away from God, they would be cursed.

*God reminded them that if they turned away from God, they were to be cursed.

*God reminded them that if they turn away from God, they will be cursed.

What would be the correct one?

A: You're not really asking about if, but about how to use tenses.
God said "If you turn away from me you will be cursed".
"God reminded them that if they turned away they would be cursed." There is no problem with this, it's the simplest way of restating what was said in the past.
"...if they have turned away" suggests that there's a strong possibility that they already have.
"They were to be cursed" suggests that the cursing was definitely going to happen.


text:
Q: Getting Problem in apache server while deploying spring boot application on tomcat 9: Status 404 - Not Found enter image description hereI have developed application that is build in spring boot which is working fine in my local but while deploying on production i'm getting error.
HTTP Status 404 - Not Found
Description: The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

A: Check your tomcat health

*

*Remove your war and start it

*Go to localhost:port and a tomcat home page must be renderized:

If your tomcat does not show the expected home page, try to fix it before to deploy your app.
Possible cause
According to your comments, you issue could be this:
You java web app shows the home page in your localhost (eclipse) at:
http://localhost:8080

But when you deploy in a tomcat, you are using a war file which is deployed in webapps folder. For example:
acme-web.war

So if you deploy this war in your tomcat hosted in
http://localhost:1234 (which must render the tomcat home page)

Your app will be available at:
http://localhost:1234/acme-web

There is a technique to show your web instead the tomcat home page. Just ask me!
I hope this helps you.


text: Q: Redirect in Wordpress based on customer type using cookies or sessions Our business has two distinct customer groups- we'll call them A and B.  A will go to our normal website and B will be redirected to a specific website we own for those types of customers.  What I'd like to do is when visitors first come to our site is to set a cookie based on whether they click on the picture of Customer type A or the picture of Customer type B.  I think the best way to do this would be to take them to a page after they click one of the pictures and then set a cookie, and then redirect them based on the cookie (or just using a meta refresh for simplicity).  What code could I use on that initial page (we'll call it the home page for simplicity) that would check for the cookie and if they have it, would redirect them to the correct pages (call them Site A and Site B), or if they don't have cookies, would still allow them to click the image that fits them and then be taken to the proper meta refresh?  I don't want anyone without cookies to be stuck in a loop.  If it matters, I am running on a Wordpress site, so PHP or Javascript codes are best.


text:
Q: Started DBAN on an external by accident - can I get my data back? I was running DBAN on a laptop HDD and I had an external HDD attached. Without realising that, I ran DBAN in auto mode. Completely stupid, I know.
I noticed it was attached when the operation started, and in a panic I pulled the external out of the USB port.
Then I attached it to my other laptop, and Windows knows there's a device plugged in, and what it's called, but didn't show up in My Computer.
So I opened up disk management and added a small 8MB partition. Now it shows up in My Computer but says it needs to be formatted before use. Obviously I don't want to do that. Disk management shows the 8MB partition and 931.47GB unallocated.
It's a ~1TB Western Digital My Passport drive and had around ~250GB free before the... accident.
The drive was plugged in to the DBANning laptop for maybe 5 seconds, it hadn't even reached 1%.
I know I'm an idiot (feel free to remind me) - what, if anything, can I do, save taking it somewhere expensive?
Edit: Just to make sure no one thinks I've run off. I ran EaseUS Partition Recovery yesterday and it returned nothing, but now I'm running EaseUS Data Recovery and it's found a lot of files. It's not complete yet (about 16.5 hours left!) but I'll update then.

A: Grab a Linux LiveCD (like Ubuntu), boot up into that environment, and plug the drive in.  It should auto-recognize the drive, and it will allow you to re-build the partition table without wiping data.  If that's too advanced for you, you also should be able to recover the data straight through Linux.  You'll just need an extra drive to move the data to.

A: Accidental DBAN? That's unlucky.
The whole point of that utility is to obliterate data beyond recovery.
Fortunately you didn't let it run for long.
Your data (most of it at least) is still there, however your partition table is corrupted and needs to be repaired.

A: I am not sure that rebuilding the partition table will even work because the files index is probably gone so there will be nothing to tell the OS what files are where.
What you need to do is use file recovery software to recover the files you want. I've used Recuva before and it was good, free too.

A: TestDisk to the rescue!  You can use TestDisk to recover/repair the filesystem on the disk, and then proceed to attempt a data recovery.  Unlike dd, TestDisk will actually recover things on the filesystem-level (i.e. it will allow you to browse through the disk and select files/folders to recover, and you can set how to handle bad sectors manually).
Of course, some of your data may be lost, and depending on what parts of the drive DBAN has overwrote, it may not fully recover all (if any) files on the drive.  That being said, this is your best bet.
The basic process would be to scan the drive, select the partitions of interest, restore/fix the partition table & headers (if required), and back up your data.  Assuming the filesystem wasn't corrupted, it's much easier to fix the partitions with TestDisk and re-copy your data from your operating system.  However, if you suspect any kind of corruption which might make copying under an OS unfeasible, TestDisk can also be used to recover your files.

Also, if you really need to those files, I would immediately make a dd backup of the drive (just incase you modify the drive during the recovery procedure, at least you can then restore it to it's original state).

A: I was in a similar situation many years ago, and I paid for this software after the demo found the files.
http://www.dtidata.com/recover_it_all.htm

Recover It All! Effective data recovery software for restoration of data lost due to accidental format, deleted files, and virus attacks. Recovers and restores deleted or damaged partition or boot sectors. Designed for FAT, FAT 32 and Windows 2000, XP, Vista and Window 7.

I was able to boot to a CD, and recover everything. Their little CD is better than freeware recuva.


text:
Q: Get all parents using Entity Framework 6 and LINQ - parent-child relationship I am trying to get all parents for a given Category as efficient as possible. I have found some old threads suggesting to use cte and view in the database but preferably I would like to avoid creating these altogether. Is there anyway I can do this without having to do multiple round trips to the database getting every parent until parent is null? If possible I would like to do it using LINQ Dot Notation.
https://stackoverflow.com/a/11929928/3850405
https://code.msdn.microsoft.com/windowsdesktop/Recursive-or-hierarchical-bf43a96e
Model:
public class Category
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    public string Name { get; set; }

    public int? ParentId { get; set; }

    public virtual Category Parent { get; set; }

    public virtual ICollection<Category> Children { get; set; }
}


text:
Q: Autotable create Nested table No Write DATA Hi all the nested table does not write the data inside, but leaves it in the main cell. what am I doing wrong ???
var doc = new jsPDF('l','mm','a3');
        doc.autoTable({
        theme: 'grid',
        columns: columns,
        body: rows,
        didDrawCell: function (data) {
            if (data.column.raw.displayEvent && data.cell.section === 'body') {
                var EventData = data.cell.text;
                doc.autoTable({
                    columns: miniColumns,
                    body:EventData,
                    didParseCell: function(dataEvent) {
                      if (dataEvent.column.raw.displayEvent === 'Opt'){
                          dataEvent.row.styles.textColor = [255,0,0]
                        }
                      },
                    startY: data.cell.y + 2,
                    margin: {left: data.cell.x + data.cell.padding('left')},
                    tableWidth: 'wrap',
                    styles: {
                        fontSize: 7,
                        cellPadding: 0.5,
                    },
                    columnStyles: {
                            Icona: {cellWidth: 8},
                            Title: {cellWidth: 8},
                            Note:  {cellWidth: 8},
                            Opt:   {cellWidth: 8},
                     }
                });
            }
        },

    });

My Complete Example
https://jsfiddle.net/max1974/bnLt6xsg/791/


text:
Q: How to calculate the shaded area of this 1/4 circle?
First I calculate the area of 1/4 circle, that is $\frac{1}{4}\pi.r^2=\frac{1}{4}\pi.4^2=4\pi.$
Then I know the area of each 1/2 circles inside the 1/4 circle is $\frac{1}{2}\pi.2^2=2\pi.$ But I know it's not as simple as 1/4 circle $-$ 1/2 circles inside. I'm having a hard time determining the shaded area that is the intersection of two 1/2 circles inside. Any idea of the steps for this solution? Thanks in advance.

A: I think this method would help you.

I learned a similar problem at school before.

A:
Let origin $O(0,0)$ be the center of quarter circle (as shown in the figure).
Now we have following equations of quarter and semi-circles
$$x^2+y^2=16$$
$$x^2+(y-2)^2=4$$ $$(x-2)^2+y^2=4$$
It's worth noticing that the straight line $y=x$ divides the required area into two equal parts. Therefore the total required area is twice the area of one part under $y=x$ which is twice the sum of areas $A_1, A_2$ & $A_3$ (as shown in above figure) given as follows
$$2(A_1+A_2+A_3)=2\left(\int_0^2\left(x-\left(2-\sqrt{4-x^2}\right)\right)dx+\int_2^{2\sqrt2}\left(x-\sqrt{4-(x-2)^2}\right)dx+\int_{2\sqrt2}^4\left(\sqrt{16-x^2}-\sqrt{4-(x-2)^2}\right)dx\right)$$  (Rearranging the terms) $$=2\left(\int_0^{2\sqrt2}xdx+\int_0^2(\sqrt{4-x^2}-2)dx+\int_{2\sqrt2}^4\sqrt{16-x^2}\ dx-\int_{2}^4\sqrt{4-(x-2)^2}dx\right)$$
$$=2\left(\left[\frac{x^2}{2}\right]_0^{2\sqrt2}+\left[\frac x2\sqrt{4-x^2}+2\sin^{-1}\left(\frac x2\right)-2x\right]_0^2+\left[\frac x2\sqrt{16-x^2}+8\sin^{-1}\left(\frac{x}{4}\right)\right]_{2\sqrt2}^4-\left[\frac{(x-2)}{2}\sqrt{4-(x-2)^2}+2\sin^{-1}\left(\frac{x-2}{2}\right)\right]_{2}^4\right)$$ $$=2\left(4+\pi-4+4\pi-4-2\pi-\pi\right)$$
$$=4\pi-8$$

A:
${}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}$

A: Let $A_1$ and $A_2$ denote the circular segment of the circle of radius $r_1 = 4\ \mathrm{cm}$ and $r_2 = 2\ \mathrm{cm}$, respectively, from $\theta = 0\ \mathrm{rad}$ to $\pi / 2\ \mathrm{rad}$.
We see that the convex shaded shape has the area of $2 A_2$, and that the other shaded shape has the area of $A_1 - 2 A_2$. Hence the total area is $A_1$.


text:
Q: How Do I Resolve Links with Python? This function takes a string as an input, and if the string starts with http:// or the string starts with https://, the function will assume that the string is an absolute link. If the URL starts with /, the function will convert it to an absolute link.
Note that base is a global variable for now. My main concern is that this function is making too many assumptions. Is there a way to accomplish the task of resolving URLs without so many assumptions?
def get_url(item):
    #absolute link
    if item.startswith('http://') or item.startswith('https://'):
        url = item
    #root-relative link
    elif item.startswith('/'):
        url = base + item
    else:
        url = base + "/" + item
    return url

A: Use urljoin from the urlparse module.
from urlparse import urljoin

base = 'http://myserver.com'

def get_url(item):
    return urljoin(base, item)

urljoin handles absolute or relative links itself.
Examples
print get_url('/paul.html')
print get_url('//otherserver.com/paul.html')
print get_url('https://paul.com/paul.html')
print get_url('dir/paul.html')

Output
http://myserver.com/paul.html
http://otherserver.com/paul.html
https://paul.com/paul.html
http://myserver.com/dir/paul.html

A: 1-Use regex
2-Add a trailing / to you base url
import re
base = 'http://www.example.com/'

def get_url(item):
    #absolute link
    pattern = "(http|https)://[\w\-]+(\.[\w\-]+)+\S*"  # regex pattern to approve http and https started strings
    if re.search(pattern, item):
        url = item
    #root-relative link
    else:
        url = base + item.lstrip('/')
    return url


text: Q: Trouble figuring out angular routing I have a page that is all in angular, when you click a link it takes you to a newpage that does not have any angular.  When I click the back button in the broswer, the url changes to expected url,but the page does not reload.  Does this sound familiar?  Any help?


text:
Q: Confused about the sequence of tenses in these sentences I came across these recently:

*

*She used to write this shopping list in squiggles, and then come back with only half the stuff that she'd gone for.

*She might have forgotten something and come to fetch it.
In sentence 1, 'come back', not 'came back' is used.
In sentence 2, 'come', not 'came' is used.
Both dialogues are referring to the past. What kind of structure/rule is this?
Note: 1 is a dialogue I heard on TV. 2 is a dialogue from a book.

A: Come is an irregular verb. The past tense of come is came. The past participle of come is come.

She used to write this shopping list in squiggles, and then [used to] come back with only half the stuff that she'd gone for.

Both write and come are infinitives here. They are both related to the same verb, used to. The author omitted the second used to to avoid repetition.

She might have forgotten something and [might have] come to fetch it.

Again, the author omitted the second might have to avoid repetition. Both forgotten and come are past participles.

The omission of words that can be understood from the context is called ellipsis. Here are some examples from the site I just linked to:

We went for a walk and [we] took some lovely photographs.
He wrote to [everyone he could think of who might help] and [he] phoned everyone he could think of who might help.
I can remember his face but [I] can't remember his name.
Do you want to stay in or [do you want to] go out tonight?


text:
Q: How foreach array json in react native? When the display elements are not the same I have a array that contains 5 elements:
[
  {
    "id": 1,
    "title": "Title 1",
    "description": "descriptions"
  },
  {
    "id": 2,
    "title": "Title 1",
    "description": "descriptions"
  },
  {
    "id": 3,
    "title": "Title 1",
    "description": "descriptions"
  },
  {
    "id": 4,
    "title": "Title 1",
    "description": "descriptions"
  },
  {
    "id": 5,
    "title": "Title 1",
    "description": "descriptions"
  }
]

And I want them to show up as follows:
<Item>
  <Text style={styles.cardText}>Title 1</Text>
  <Text style={styles.cardText} numberOfLines={2}>Description 1</Text>
</Item>
<Grid>
  <Col>
    <Item>
      <Text style={styles.cardText}>Title 2</Text>
      <Text style={styles.cardText} numberOfLines={2}>Description 2</Text>
    </Item>
  </Col>
  <Col>
    <Item>
      <Text style={styles.cardText}>Title 3</Text>
      <Text style={styles.cardText} numberOfLines={2}>Description 3</Text>
    </Item>
  </Col>
</Grid>
<Grid>
  <Col>
    <Item>
      <Text style={styles.cardText}>Title 4</Text>
      <Text style={styles.cardText} numberOfLines={2}>Description 4</Text>
    </Item>
  </Col>
  <Col>
    <Item>
      <Text style={styles.cardText}>Title 5</Text>
      <Text style={styles.cardText} numberOfLines={2}>Description 5</Text>
    </Item>
  </Col>
</Grid>

How to display the above as in React Native?
I tried to use datas.map function but could not.
I tried to adding string but I thought that was not the solution.
Is there a solution for it?
Thank all.

A: You can chunk the array into 2 parts for indexes other than 0.
constructor() {
    super();
    this.state = {
        data: [
            {
                "id": 1,
                "title": "Title 1",
                "description": "descriptions"
            },
            {
                "id": 2,
                "title": "Title 1",
                "description": "descriptions"
            },
            {
                "id": 3,
                "title": "Title 1",
                "description": "descriptions"
            },
            {
                "id": 4,
                "title": "Title 1",
                "description": "descriptions"
            },
            {
                "id": 5,
                "title": "Title 1",
                "description": "descriptions"
            }
        ],
        chunk: this.chunk
    }
}

Method for chunking array:
chunk(array, chunkSize) {
    return [].concat.apply([],
        array.map(function (elem, i) {
            return i % chunkSize ? [] : [array.slice(i, i + chunkSize)];
        })
    );
};

Rendering the items:
render() {
    let { data, chunk } = this.state;
    let dataForChunk = [...data];
    dataForChunk.splice(0, 1); //removes 1st index of array
    let chunkedArr = chunk(dataForChunk, 2);

    return (<View style={{flex: 1}}>
        <Item>
            <Text style={styles.cardText}> {data[0].title} </Text>
            <Text style={styles.cardText} numberOfLines={2} > {data[0].description} </Text>
        </Item>
        {chunkedArr.map((arr, index) => {
            return(
                <Grid>
                    {arr.map(item => {
                        return(
                            <Col>
                                <Item>
                                    <Text style={styles.cardText} >{item.id}</Text>
                                    <Text style={styles.cardText} numberOfLines={2}>{item.description}</Text>
                                </Item>
                            </Col>
                        );
                    })}
                </Grid>
            )
        })}
    </View>)
}

A: You can use FlatList instead.
Considering example
const row = [{key: 'a'}, {key: 'b'}]

FlatList Usage:
<FlatList
        data={row}
        renderItem={(item) => this._renderItem(item)}
        keyExtractor={extractKey}
        extraData={row}
        />

Rendering View inside function:
    _renderItem = ({item}) => {
    return <Text>{item.key}</Text>
   }


text:
Q: I want to make a new dataframe with a result of randomforest predict_proba I made a randomforest classifier which has 8 classes.
rf_clf.predict_proba(X_test)

this code's result looks like
array([[0.145 , 0.025 , 0.02  , 0.01  , 0.0025, 0.07  , 0.715 , 0.0125],
   [0.    , 0.    , 0.    , 0.    , 0.    , 1.    , 0.    , 0.    ],
   [0.0925, 0.3375, 0.175 , 0.01  , 0.0625, 0.1375, 0.0875, 0.0975],
   [0.0525, 0.72  , 0.065 , 0.005 , 0.0025, 0.1125, 0.025 , 0.0175],
   [0.    , 0.    , 1.    , 0.    , 0.    , 0.    , 0.    , 0.    ],
   [0.6675, 0.0425, 0.0025, 0.0075, 0.005 , 0.0225, 0.235 , 0.0175]])

I want to make a new dataframe named 'probability' whose columns names are '1','2' ...'8'.
How can I do this?


text:
Q: edit my centos 6 network config file using PHP code but after network restart i get an error I am using a simple file operation on the PHP in order to edit the config file for network interface on CentOS 6.7(/etc/sysconfig/network-scripts/ifcfg-eth0
), after change in any value and save into the config file and try to restart the network interface i get this error:
does not seem to be present, delaying initialization.
[FAILED]

my PHP code is this:
<?php

// configuration
$file = '/etc/sysconfig/network-scripts/ifcfg-eth0';

// check if form has been submitted
if (isset($_POST['text']))
{
// save the text contents
file_put_contents($file, $_POST['text']);

// redirect to form again
header('Location: network.php');
exit();
}

// read the textfile
$text = file_get_contents($file);

?>
<!-- HTML form -->
<form action="" method="post">
<textarea style="width:50%; height:50%;" name="text"><?php echo htmlspecialchars($text) ?></textarea>
<input type="submit" />
<input type="reset" />
</form>

i need manually called the network script by command setup and do a modification in the device setting and save then i will be able to restart the network interface. appreciate if anyone help me why this issue happen while if i open the config file and edit it manually it wouldn't cause this issue.

A: It's most likely that the user name the server runs as (by default apache on most Red Hat-based distributions) doesn't have permission to write to/etc/sysconfig/network-scripts/ifcfg-eth0.
You should check the return values of:
file_put_contents($file, $_POST['text']);

From http://php.net/manual/en/function.file-put-contents.php

This function returns the number of bytes that were written to the file, or FALSE on failure.

I presume this script will only be run by your or trusted colleagues given that there's no validation of the user input. Indentation would also make the PHP code more readable.


text: Q: Brief list of improvements starting from the next Visual Studio edition after 2010 up to the latest 2017 So I tried and tried googling about this, but I can't seem to see a list of all the improvements in Visual Studio after VS2010. The reason for this is so that I'll be able to recommend our dev team to upgrade hopefully to VS2017, but if purchasing budget does not allow it, at least to something newer than 2010 because of course of new features. But I'm not familiar with any aside from the obvious look of the IDE which is now very different from 2010. I'm sure there's already a lot we're missing on the latest VS has to offer. Help will be really appreciated thanks!


text:
Q: What does crockford mean when he says that undefined cannot be a property value? In the book Javascript the good parts, on the opening page of Ch3 on objects, it states:

An object is a container of properties, where a property has a name and a value. A property name can be any string, including the empty string. A property value can be any Javascript value except for undefined.

Note: undefined is highlighted in the book to denote that is is a literal.
In practice, however, I am able to do it.
var a = { "name": undefined };

What is wrong with my understanding ?

A: I believe the answer is that he's wrong.
As you observe, you can set var a = { "name": undefined };.

*

*a.name === undefined

*a.name === a.someFakeProperty
Here's where they're different, though:

*

*'someFakeProperty' in a === false

*'name' in a === true
Or, to do it a different way,

*

*a.hasOwnProperty('someFakeProperty') === false

*a.hasOwnProperty('name') === true
Using the somewhat infamous for..in loop,
for (var i in a) {
    alert(i);
}

... will give you name.
So, by value you may not be able to distinguish undefined and undefined, but they are quite different internally.
Addition: he's wrong about the property names, too - a[window] = 43; a[window] == 43; is just fine. Sure, you can't then do a.window, but a.___ is just syntactic sugar for a['___']. As noted in the comments, property names are cast to string so I was wrong about this bit.

A: I don't like the terminology that Crockford uses, he seem to mix the concept of undefined and undeclared.
The statement:

A property value can be any Javascript value except for undefined.

Is completely wrong IMO, because undefined is a primitive value of the language.
See also:

*

*Difference between undefined and not being defined in Javascript

A: I think what he's trying to say is that a property's value cannot be undefined because undefined is exactly how JavaScript denotes properties that don't exist. In other words, if you have the following object
var a = { "name": undefined };

Then a.name is undefined, but so is a.someFakeProperty. However, as Ben Lee points out in his comment, name will still show up when you iterate the properties of a using a for loop, while someFakeProperty will not. Therefore, it seems that Crockford was a bit imprecise in conveying the idea in question here.

A: Perhaps this:
var a = {"name": x}; //x is undefined, so it will cause an error.

Just my understanding.


text:
Q: Graph of a Sine Function Increased on One Side If we want something looks like this sine wave, what is a function that will satisfy this:

Further, how can we make this go both ways, meaning either 1) a sine wave staying the same at the bottom but going upwards linearly as it progresses (as shown) or 2) a sine wave staying the same at the bottom but going downwards linearly as it progresses?
I have tried, for example, $x/2(\sin x)$, which gives us a linear increase, but I want it to increase on the top while staying the same on the bottom.
Thanks!

A: Plot[ x (1 - Sin[x]), {x, -1, 45}, GridLines -> Automatic]

You can adjust the slope $m$ of envelope, time period etc as:
$$ y= m x \;(1- \sin \dfrac{2 \pi x }{\lambda})$$
To reflect about x-axis making it go down, equation can be changed as:
Plot[ x (-1 + Sin[x]), {x, -1, 45}, GridLines -> Automatic]

A: Try $f(x)=x + x\sin x$, or something similar.


text:
Q: How to remove popup message of NFC tag in iOS? In the give image, when NFC session begin, "Ready to scan" popup appear in screen. In my application I only need to scan NFC tag without popup. Is there any solution to remove popup as shown in image?

A: Not possible with current API. I've had several discussions with Apple direct about their NFC implementation which I specifically brought up the system UI modal and if it can be disabled from showing. They basically told me it'll never happen.
If you want to consider accessing private functions then I think it is possible but your app get approved for the iTunes Store.


text:
Q: How to connect to Oracle Database from Excel 2016 I want to connect to Oracle Database from Excel 2016, to extract DB data returned by a specific query to Excel.
I don't have any DB installed on my computer. I usually connect to Oracle DB using Oracle SQL Developer which takes host name, port number and SID to get connected. In such case, how do should we set up the Excel?
Can anyone please help!


text:
Q: Static variables restriction in session beans It's impossible to use static variables on a session bean code. Is this restriction arbitrary or fundamented? And why?
Best regards

A: It is fundamental. As per this sun documenation,
Nonfinal static class fields are disallowed in EJBs because such fields make an enterprise bean difficult or impossible to distribute.  Static class fields are shared among all instances of a particular class, but only within a single Java Virtual Machine (JVM). *

A: As stated in the FAQ on EJB restrictions, one of the restrictions for using EJBs is:

enterprise beans should not read or write nonfinal static fields

Further expanded in the discussion on static fields:

Nonfinal static class fields are disallowed in EJBs because such fields make an enterprise bean difficult or impossible to distribute. Static class fields are shared among all instances of a particular class, but only within a single Java Virtual Machine (JVM). Updating a static class field implies an intent to share the field's value among all instances of the class. But if a class is running in several JVMs simultaneously, only those instances running in the same JVM as the updating instance will have access to the new value. In other words, a nonfinal static class field will behave differently if running in a single JVM, than it will running in multiple JVMs. The EJB container reserves the option of distributing enterprise beans across multiple JVMs (running on the same server, or on any of a cluster of servers). Nonfinal static class fields are disallowed because enterprise bean instances will behave differently depending on whether or not they are distributed.
It is acceptable practice to use static class fields if those fields are marked as final. Since final fields cannot be updated, instances of the enterprise bean can be distributed by the container without concern for those fields' values becoming unsynchronized.

A:
static means unique for a class OR for all it's objects.

Now, javabeans are supposed to have user-specific data, static fields don't make any sense for these.
One user edits a variable, ant it'll be updated for all other users too. (at free of cost :-)).
However if you want static behaviour for these (i.e. using same data for all users), you have application for that purpose.


text:
Q: Is a function with just one point in its domain strictly ascending and strictly descending? This is the definition of an strictly increasing and strictly decreasing function.
"A function $f(x)$ increases on an interval I if $f(b)\geq f(a)\;\;\forall b>a$, where $a,b \in I$. If $f(b)>f(a) \;\;\forall \;\;b>a$, the function is said to be strictly increasing.
Conversely, A function $f(x)$ decreases on an interval I if $f(b)≤f(a)\;\;\forall b>a$, where $a,b \in I$. If $f(b)<f(a) \;\;\forall \;\;b>a$, the function is said to be strictly decreasing.
Then how would a function with just one point in its domain be described?

A: Yes, it's both (strictly) increasing and (strictly) decreasing since there is no second point that can contradict the definitions.


text:
Q: browserID server logout so i found this browserid.org and then this [browserid.org/developers] and decided i would like to try this new authentication method that is browserID. after digging in to the only semi official example i could find ( browserid_favbeer_example ) and flipping back and forth to the 3 easy steps page i am still puzzled. i searched around a bit and found one, the javascript implementation can be easily exploited (for right now) and two, from a very nice fellow, the example below. the first thing i noticed it missing was the logout. if anybody could be so kind as to help me complete the logout it would be much appreciated.
<?php
/*
 * Simple implementation of Mozilla BrowserID (see https://browserid.org/)
 * Author : Guillaume <guillaume@atto.be>
 */
/*
 * Usage :
 *
$browserid = new BrowserID('mywebserver.com', $_POST['assertion']);
if($browserid->verify_assertion())
{
      echo('Welcome, your email is '.$browserid->get_email());
}
 */
class BrowserID
{
  private $audience;
  private $assertion;
  private $email;
  private $validity;
  private $issuer;
  private function post_request($url, $data)
  {
    $params = array('http' => array('method' => 'POST', 'content' => $data));
      return stream_get_contents($fp);
    }
    else
    {
      return FALSE;
        }
      }
      public function BrowserID($audience, $assertion)
      {
        $this->audience = $audience;
        $this->assertion = $assertion;
      }
      /*
       * Send the assertion to the browserid.org server (this must be over HTTPS)
       * The response is read to determine is the assertion is authentic
       */
      public function verify_assertion()
      {
                if(isset($result['status']) && $result['status'] == 'okay')
        {
          $this->email = $result['email'];
          $this->validity = $result['valid-until'];
          $this->issuer = $result['issuer'];
          return true;
        }
        else
        {
          return false;
        }
      }
      public function get_email()
      {
    return $this->email;
  }
  public function get_validity()
    return $this->email;
  }
  public function get_validity()
 * Usage :
 *
$browserid = new BrowserID('mywebserver.com', $_POST['assertion']);
if($browserid->verify_assertion())
{
  echo('Welcome, your email is '.$browserid->get_email());
}
 */
class BrowserID
{
  private $audience;
  private $assertion;
  private $email;
  private $validity;
  private $issuer;
  private function post_request($url, $data)
  {
    $params = array('http' => array('method' => 'POST', 'content' => $data));
      return stream_get_contents($fp);
    }
    else
    {
      return FALSE;
    }
  }
  public function BrowserID($audience, $assertion)
  {
    $this->audience = $audience;
    $this->assertion = $assertion;
  }
  /*
   * Send the assertion to the browserid.org server (this must be over HTTPS)
   * The response is read to determine is the assertion is authentic
   */
  public function verify_assertion()
  {
    if(isset($result['status']) && $result['status'] == 'okay')
    {
      $this->email = $result['email'];
      $this->validity = $result['valid-until'];
      $this->issuer = $result['issuer'];
      return true;
    }
    else
    {
      return false;
    }
  }
  public function get_email()
  {
    return $this->email;
  }
  public function get_validity()
  {
    return $this->validity;
  }
  public function get_issuer()
  {
    return $this->issuer;
  }
}// end class BrowserID
$browserid = new BrowserID($_SERVER['HTTP_HOST'], $_POST['assertion']);
if($browserid->verify_assertion())
{
  echo('Welcome '.$browserid->get_email());
}
else
{
  echo('Identification failure');
}
?>

A: I hope it's not too late to answer your question. It was noticed in the BrowserID mailing list, but unfortunately no one came back here to answer you.
After you authenticate with BrowserID, you set an authentication cookie and based on the cookie you can determine if the user is valid. Then to log out, you offer the user a link that will have you delete that cookie.

A: Joe's answer is right, Persona doesn't replace your existing session management so you still have to create and delete your cookies.
However, the new Persona/BrowserID API now has a navigator.id.logout() function that you should call, as well as a "onlogout" callback inside the navigator.id.watch() where you specify what happens when users logout (i.e. cookies get deleted):
https://developer.mozilla.org/en-US/docs/DOM/navigator.id#ObserverMethods


text:
Q: Calling an external mindict.exe file into Java project How can I use the Minutiae Extractor (Mindict.exe) provided by NIST in my Java Application. I want to extract minutiae using mindict.exe, Actually I want the solution about what will be the code or which class can I use to call an external .exe file in my Java program.
Note: - I have not written code for this till time.


text:
Q: How can I set the height of my first UITableViewCell higher than the others? I am trying this in my viewDidLoad():
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return 300.0
    }
    return 100.0
}

but this has no effect

A: In Swift 3 Write code in following way
Height for row is a tableView delegate method so you do. not write inside of ViewDidLoad method, you can write in outside of viewDidLoad method
import UIKit
class ProfileViewController: UIViewController,ProfileViewControllerDelegate {

    //MARK: - Outlet -

    @IBOutlet weak var tblView: UITableView!

    //MARK: - View Life Cycle -
    override func viewDidLoad() {

    }

    //MARK: TablView Delegate
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0 {
            return 300.0
        }
        return 100.0

}

A: This is the example of simple tableView which first row height is 300 and other's 100.
    import UIKit
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView: UITableView!

        override func viewDidLoad() {
            super.viewDidLoad()
            tableView.delegate = self
            tableView.dataSource = self
        }

        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

            let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "CellID") as UITableViewCell!

            cell.textLabel?.text = "testing"

            return cell
        }

        // method to run when table view cell is tapped
        func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            print("You tapped cell number \(indexPath.row).")
        }

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return 300.0
    }
    return 100.0
}

}


text:
Q: Add icons to alternating UITableViewCell I have an NSMutableArray filled with the ratings of items, that I get returned from my query (web). Now lets say I have the items "one", "two" and "three" in my table view. And only "one" and "three" have been rated, then I get the two ratings back for those items when I do my query, and if in my cellForRowAtIndexPath:method I just do. something like
cell.rating = ratingsArray[indexRow.path];

Where cell.rating is an attribute in my cell
Then the item two will have what should be threes rating...
Do you see the problem? And how I could get around it?
Thanks for the help :)
EDIT
myArray = @[@"one", @"two", @"three"];

PFQuery *query = [PFQuery queryWithClassName:@"AverageRating"];
[query whereKey:@"item" containedIn:myArray];
[query findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
    if (results) {
        NSLog(@"%@", results);

    }
}];

And I don't know which have been rated.

A: Now the value in the array may be [4,3]
The value in the array should be [4,0,3] as 4,0,3 represent individual ratings
hence the problem can be fixed
ir return 0 or any unused valid value for rating when there is none available

A: Sounds like a good use for NSNull. Put NSNull into the array for "no rating", and then when you are determining what to display in your UI, see if the value in the array is NSNull or not.

A: What you need is a way to determine if the cell has a rating or not. Here is a simple solution. Instead of using an NSMutableArray to hold your ratings, you should use an NSMutableDictionary.
The dictionary should be structured so that the "Keys" can be the index to which the rating corresponds. So your dictionary can look something like this:
Key: 0 Value: rating for first cell
Key: 2 Value: rating for cell three
Inside your cellForRowAtIndexPath: method, you can do a check to see if the dictionary contains a key corresponding to the indexPath.Row value and if it does, you can set a rating for the cell.
Code:
Get your data represented using a dictionary instead:
NSMutableDictionary *ratingsDictionary = [[NSMutableDictionary alloc] init];
[myDictionary setObject:rating1 forKey:[NSNumber numberWithInt:0]]
[myDictionary setObject:rating3 forKey:[NSNumber numberWithInt:2]]

Add this to your cellForRowAtIndexPath: method
if ([ratingsDictionary objectForKey:[NSNumber numberWithInt:indexPath.Row]])
{
    cell.rating = [ratingsDictionary valueForKey:[NSNumber numberWithInt:indexPath.Row]];
}


text:
Q: Creating SEO Friendly URLs with .htaccess and php I'm trying to generate SEO friendly URLs using PHP by using a rewrite in our .htaccess file, but I can't get it to work (I've researched many of the related topics on StackExhange and elsewhere, but to no avail).
I'm attempting to make the content of this URL: http://199.119.123.135/surety-bonds/city.php?state=california&city=sacramento
...also display on the cleaner URL version here: http://199.119.123.135/surety-bonds/california/sacramento/
I'm using the following code in my .htaccess file:
RewriteEngine on
RewriteRule ^surety-bonds/([a-zA-Z]+)$ city.php?state=$1&city=$2 [L,NC]

Any idea why the cleaner URL displays a 404 error?
Thanks!

A: Try:
RewriteEngine On

RewriteCond %{THE_REQUEST} \ /+surety-bonds/city\.php\?state=([^&]+)&city=([^&\ ]+)
RewriteRule ^ /surety-bonds/%1/%2/? [L,R]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^^surety-bonds/([^/]+)/([^/]+)/?$ /surety-bonds/city.php?state=$1&city=$2 [L,QSA]

in the htaccess file in your document root.


text:
Q: Update Order column with number increasing (depend on ID column) I'm using the SQL Server 2008.
Now I have the scenario as description below:

*

*1 table with 3 columns: ID, Name, Order.

*They has 8 records.

*5 records have the same data: ID='1', Name='AAA'

*3 records have the same data: ID='2', Name='BBB'

Now I want to update Order column with number increasing (start from 1) for each ID,Name:
    No  Name    Order
1   AAA 1
1   AAA 2
1   AAA 3
1   AAA 4
1   AAA 5
2   BBB 1
2   BBB 2
2   BBB 3

How can I get this result without using Cursors?
I'm very appriciated for your help.
Thanks.

A: You can try the following.  I use CTE to drive the update statement
WITH data AS
(
    SELECT Order
           , ROW_NUMBER() OVER (PARTITION BY ID, NAME
                                ORDER BY ID, NAME) AS Seq
      FROM TableA
)
UPDATE data
   SET Order = Seq

Substitute TableA with your table name