text:
Q: DBContext, access navigational property of newly Added entity I am trying to access Navigational property of entity having State = Added, but the Navigational property is null.
    using (var myc = new DBTestEntities())
    {
        var cust = new Customer();
        cust.CustomerName = "New Customer";
        cust.BusinessTypeID = 1;  // This is a valid BusinessTypeID present in BusinessType table

        myc.Customers.Add(cust);
        // at this point cust.BusinessType is null
        Console.WriteLine(cust.BusinessType.BusinessTypeName);
    }

Can anyone guide my how to access Navigational property in this case.

A: You need to have a BusinessType Property in your Customer Class.
There you can set the Businesstype something like :
cust.BusinessType = (from x in myc.BusinessTypes where x.Id=1 Select x).First();

A: I think you need to do:
myc.SaveChanges();

to actually submit the enitity to the database.

A: After the line
myc.Customers.Add(cust);

you can add
myc.ChangeTracker.DetectChanges();

This will trigger a process called relationship fixup, in which EF synchronizes all properties involved in foreign keys. It will cause the BusinessType object to be fetched from the database if it is not in the context yet.


text:
Q: Fixing EFI Windows boot from Linux Basically I've lost my Windows 8 boot option and the boot repair from Windows installation media doesn't fix the problem.
I know this is more-or-less a Windows' problem but I'm seeking a efibootmgr solution rather than a solution that uses the much more awkward Windows based bcdedit command. Hence I ask here instead of super user.
The detailed background is here, basically my system was initial setup in BIOS/MBR/CSM mode, Windows 10 is refusing to be installed there, so I have to converted my MBR disk to GPT. I got everything on the Linux side working afterward, but fixing Windows boot via Windows installation media failed.

*

*All my Linux OS/partitions were found by update-grub, but my Windows 8 is missing from the GRUB menu.

*The os-prober was not able to list/find my Windows 8 either.

I hope the fix is simply adding my Windows 8 back as an boot entry using efibootmgr, but this is where I got lost and need help. Again further detailed like current partition schema can be found here. Thx.
Maybe my Windows 8 was installed in BIOS/MBR/CSM mode, and has no EFI booting capability as I don't see a /EFI directory within it? Here are all root level directories in my Windows 8 partition:
$Recycle.Bin/              ProgramData/
$WINDOWS.~BT/              Programs/
$Windows.~WS/              Recovery/
BOOTNXT                    Recovery.txt
BOOTSECT.BAK               System Volume Information/
Boot/                      Tmp/
Documents and Settings/    Users/
ESD/                       Windows/
Intel/                     bootmgr
Program Files/             pagefile.sys
Program Files (x86)/       swapfile.sys

Or maybe I don't need efibootmgr at all, just a custom entry in /etc/grub.d/40_custom like the following?
menuentry "Windows 8 BIOS MBR" {
     insmod part_msdos
     insmod ntldr
     insmod ntfs
     ntldr (hd0,msdos1)/bootmgr
}

A: OK, as per @FelixJN's request, here is the answer instead of a link.
My purpose was to seek a Linux based solution, as at least using ntldr  loading Windows' bootmgr were the trick I used to use back in the old grub / grub4dos days. Like, this should work:
menuentry "Windows 8 UEFI/GPT" {
    insmod part_gpt
    insmod search_fs_uuid
    insmod chain
    search --fs-uuid --no-floppy --set=root 28cf-35de
    chainloader ($root)/EFI/Microsoft/Boot/bootmgfw.efi
}

but I didn't try it as I don't have much faith in grub2 and its documentation, but turned to the solution from Windows instead, just as @telcoM summerized,

run the boot repair process in UEFI mode to write the Windows UEFI bootloader onto the ESP partition

Here are the details steps taken from here.

*

*Insert the Media (DVD/USB) in your PC and restart.

*Boot from the media.

*Select Repair Your Computer.

*Select Troubleshoot.

*Choose Command Prompt from the menu :

*

*Type and run the command :
diskpart

*Type and run the command :
sel disk 0

*Type and run the command :
list vol

*Verify that the EFI partition (EPS - EFI System Partition) is using the FAT32 file system and assign a drive letter to it (Assign a letter that isn't already in use.):

*Type and run the command :
 sel vol <number of volume>

*Type and run the command :
 assign letter=<drive letter>:

*Type and run the command :
 exit

*In order to repair the boot record :

*

*Type and run the command :
cd /d <drive letter>:\EFI\Microsoft\Boot\

*Type and run the command :
bootrec /FixBoot

The next step is the same across all the operating systems at this point :

*

*Rebuild the BCD store

*First run the command below to backup the old BCD :
 ren BCD BCD.old

*Now recreate it using this command :
 bcdboot c:\Windows /l en-us /s <boot letter>:All

redpajama_set_name: RedPajamaStackExchange


text:
Q: KeyCloak Group ID in Token missing I am currently setting up a fresh KeyCloak instance and I am trying to achieve the following:
Users will be placed in
- Groups
- These Groups will get client specific roles
For example I have the Role "Publishers" and several groups of publisher: Publisher1, Publisher2, ...
So, when a user logs in, I can determine whether he is a publisher or not and then give him access to a specific set of features on the website.
The groups shall then narrow down all infos he will receive.
Just like the role will give him access to a REST API and the group will filter the results he will receive.
In SQL: SELECT * FROM xyz where publisher_id = ?
In the token I want to see these infos. When using the evaluate feature I currently receive this:
{
  "jti": "3e96fc9d-b1dc-428a-8f8e-0661f9cf265b",
  "exp": 1578303161,
  "nbf": 0,
  "iat": 1578302861,
  "iss": "https://prodo-sso-ti.ariva-services.de/auth/realms/PRODO",
  "aud": "account",
  "sub": "55bed571-dd3b-4282-8688-5da543517a49",
  "typ": "Bearer",
  "azp": "dashboard",
  "auth_time": 0,
  "session_state": "12ab2b8c-dc9a-42ca-b106-1a213dd38fc0",
  "acr": "1",
  "allowed-origins": [
    "https://secretlink"
  ],
  "realm_access": {
    "roles": [
      "offline_access",
      "uma_authorization"
    ]
  },
  "resource_access": {
    "account": {
      "roles": [
        "manage-account",
        "manage-account-links",
        "view-profile"
      ]
    },
    "dashboard": {
      "roles": [
        "Publisher"
      ]
    }
  },
  "scope": "openid profile email",
  "group_membership": [
    "/Publisher1"
  ],
  "email_verified": true,
  "name": "My Name",
  "preferred_username": "mb",
  "locale": "de",
  "given_name": "My",
  "family_name": "Name",
  "email": "my@name.de"
}

I activated the Group Membership Mapper to get the Groups the user is in.
The problem is, that I only get the name of the Group while I need something more useful, like an ID.
So I tried to add an attribute to group "publisher_id" with numeric value "1".
How is it possible to get also this publisher_id in the group membership infos or somewhere else.
Or maybe I am on a wrong way and this could be achieved somehow different?
I appreciate any hints :)

A: There is an easy way to add Groups Id to token:

*

*Create a new Client Scope for your Client:

Clients Scopes -> Create -> Client Scope Template(Audience template) -> your_client_name

*Create a new Mapper in your new Client Scope

Clients Scopes -> your_client_name -> Mappers -> Create

*Set some name, Mapper Type must be Script Mapper
and then paste this code to Script section:
/**
 * Available variables:
 * user - the current user
 * realm - the current realm
 * token - the current token
 * userSession - the current userSession
 * keycloakSession - the current userSession
 */

//insert your code here...
var groups = [];
for each (var group in user.getGroups()) groups.push(group.getId());
token.setOtherClaims("groups_ids",
    Java.to(groups, "java.lang.String[]")
);

Do not forget to set Add to access token.
You will see it in your token:
groups_ids

A: by this curl you can find out which roles are available for a special group:
curl --location --request GET 'http://localhost:8080/auth/admin/realms/adanic/groups/35324d42-3299-4ed3-ad07-8c9ea8c02e9b/role-mappings/realm/available'

and by this curl you can get list of users with special role:
curl --location --request GET 'http://localhost:8080/auth/admin/realms/adanic/roles/adanic-admin/users?first=0&max=100' \
--header 'Content-Type: application/json' \
--data-raw '{
   "roles": [
       {
           "id": "0830ff39-43ea-48bb-af8f-696bc420c1ce",
           "name": "user",
           "description": "${role_create-client}",
           "composite": false,
           "clientRole": true,
           "containerId": "kilid"
       }
   ]
}'

i wish it could help

A: Your question is bit old now - but I have a comparable problem and even don´t have the possibility to store attributes in groups (since I´m using a custom UserStoreProvider).
An "easy" solution solution would perhaps be to implement a custom OIDCAccessTokenMapper and create your needed token on your own. It´s not very complicated to implment one based on AbstractOIDCProtocolMapper.
More or less you just have to implement and deploy a jar to your keycloak with a single class (extending the abstract class), wich implements
@Override
protected void setClaim(IDToken token, ProtocolMapperModel mappingModel, UserSessionModel userSession, KeycloakSession keycloakSession, ClientSessionContext clientSessionCtx)

and  reference this class in a spi descriptor file org.keycloak.protocol.ProtocolMapper
You then have to activate the "protocol mapper" in your keycloak client configuration.

A: the main idea is to extend the keycloack

*

*Download keycloak-extends-0.0.1.jar

*Copy keycloak-extends-0.0.1.jar to keycloak-15.0.2\standalone\deployments

*

*Login to Keycloak

*Select realm

*Open client scopes page

*Click create

*Create new openid client (or edit existing one)

*Open the created client

*Click on mappers tab

*Click on create

*Select mapper type group id

*Enter name and token claim name

*Click save


text:
Q: How to delete url in git I am pushing data to github. When I push data i am facing problem.I am pushing data using this.
git init
touch README.md
git add .
git commit -m "initial commit"
git remote add origin https://github.com/YourAccount/firstPush.git
git push -u origin master

Actuall I run  git remote add origin https://github.com/YourAccount/firstPush.git this command wrong.
When I again push data with correct path I got error
fatal: remote origin already exists.

A: You can follow any of the following 3 methods:

*

*Remove the old origin and readd the correct one:
git remote remove origin
git remote add origin <correct address>

*Update the existing remote links:
git remote set-url origin <correct url>

you can optionally provide --push to the above command.

*Update the remote section of your .git/config file:
[remote "origin"]
    url = <correct url>
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

You can also refer to git documentation for the git remote commands.

A: Use this command
$ git remote set-url <remote repository url>

A: Find the .gitconfig file in your local computer.
Open it with notepad and delete the urls from there.
The following command will show you where your url is living.
git config --list --show-origin


text:
Q: Collect array with same id inside array and create new array with id, and name javascript {
   "workRequestCompleted":[
      {
         "number":"4329502",
         "name":"Scheduled Outage Primary Feeder",
         "startDate":"2019-07-01",
         "endDate":"2019-07-10",
         "lastUpdate":"2019-12-01T05:00:00Z",
         "contractId":null,
         "status":"Scheduled"
      }
   ],
   "prerequisites":[
      {
         "preq_id":"M12345",
         "preq_type":"FLAG",
         "preq_date_time":"2019-10-02T03:28:00Z",
         "preq_last_update":"2018-12-03T13:30:00Z",
         "preq_crew_id_id":"W_FOD_013",
         "wr_number":"4329502",
         "preq_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      }
   ],
   "workComponents":[
      {
         "wc_number":"888-FOD-CO-950-609",
         "wc_type":"PSMECH",
         "wc_description":"Make halves, pick up VS1234.",
         "wc_crew_id":"W_FOD_013",
         "wc_start_date_time":null,
         "wc_end_date_time":null,
         "wc_estimated_hours":10.0,
         "wc_scheduled_start_date_time":"2020-02-16T19:23:02.866019Z",
         "wc_scheduled_end_date_time":"2020-02-17T19:23:02.866028Z",
         "wc_actual_hours":0.0,
         "wc_status":"Scheduled",
         "wc_notes":null,
         "wc_number_pre":"888-FOD-CO-178-0",
         "wc_number_post":"",
         "delay_type":null,
         "wr_number":"4329502",
         "wc_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      },
      {
         "wc_number":"888-FOD-CO-178-0",
         "wc_type":"PSMECH",
         "wc_description":"Make halves, pick up VS1234.",
         "wc_crew_id":"W_FOD_013",
         "wc_start_date_time":"2019-12-02T04:28:00Z",
         "wc_end_date_time":"2019-12-03T13:30:00Z",
         "wc_estimated_hours":10.0,
         "wc_scheduled_start_date_time":null,
         "wc_scheduled_end_date_time":null,
         "wc_actual_hours":10.0,
         "wc_status":"Pending\n",
         "wc_notes":"We noticed that VS5678 may require additional maintenance soon.",
         "wc_number_pre":"",
         "wc_number_post":"",
         "delay_type":"",
         "wr_number":"4329502",
         "wc_crew":{
            "crew_id":"W_FOD_013",
            "crew_name":"Pre-req 1",
            "expertise":"Flush"
         },
         "facilities":[
            {
               "facility_id":"VS1234",
               "facility_type":"VAULT",
               "facility_lat":40.758896,
               "facility_long":-73.98513,
               "facility_notes":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
            }
         ]
      }
   ]
}

I have that JSON that contain array, I want to combine facility array that have same facility id from Prerequisites and WorkComponents array and create new array that contain facility id and preq_type with wc_type separate by comma if it have a same facility id, how I can do in javascripts?, thanks
Expected Result :
[
        {
            "facility_id": "VS1234",
            "type": ["FLAG", "PSMECH", "PSMECH"]
        }
]

A: You can use multiple forEach loops and build one object.

const data = {
  workRequestCompleted: [
    {
      number: "4329502",
      name: "Scheduled Outage Primary Feeder",
      startDate: "2019-07-01",
      endDate: "2019-07-10",
      lastUpdate: "2019-12-01T05:00:00Z",
      contractId: null,
      status: "Scheduled"
    }
  ],
  prerequisites: [
    {
      preq_id: "M12345",
      preq_type: "FLAG",
      preq_date_time: "2019-10-02T03:28:00Z",
      preq_last_update: "2018-12-03T13:30:00Z",
      preq_crew_id_id: "W_FOD_013",
      wr_number: "4329502",
      preq_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    }
  ],
  workComponents: [
    {
      wc_number: "888-FOD-CO-950-609",
      wc_type: "PSMECH",
      wc_description: "Make halves, pick up VS1234.",
      wc_crew_id: "W_FOD_013",
      wc_start_date_time: null,
      wc_end_date_time: null,
      wc_estimated_hours: 10.0,
      wc_scheduled_start_date_time: "2020-02-16T19:23:02.866019Z",
      wc_scheduled_end_date_time: "2020-02-17T19:23:02.866028Z",
      wc_actual_hours: 0.0,
      wc_status: "Scheduled",
      wc_notes: null,
      wc_number_pre: "888-FOD-CO-178-0",
      wc_number_post: "",
      delay_type: null,
      wr_number: "4329502",
      wc_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    },
    {
      wc_number: "888-FOD-CO-178-0",
      wc_type: "PSMECH",
      wc_description: "Make halves, pick up VS1234.",
      wc_crew_id: "W_FOD_013",
      wc_start_date_time: "2019-12-02T04:28:00Z",
      wc_end_date_time: "2019-12-03T13:30:00Z",
      wc_estimated_hours: 10.0,
      wc_scheduled_start_date_time: null,
      wc_scheduled_end_date_time: null,
      wc_actual_hours: 10.0,
      wc_status: "Pending\n",
      wc_notes:
        "We noticed that VS5678 may require additional maintenance soon.",
      wc_number_pre: "",
      wc_number_post: "",
      delay_type: "",
      wr_number: "4329502",
      wc_crew: {
        crew_id: "W_FOD_013",
        crew_name: "Pre-req 1",
        expertise: "Flush"
      },
      facilities: [
        {
          facility_id: "VS1234",
          facility_type: "VAULT",
          facility_lat: 40.758896,
          facility_long: -73.98513,
          facility_notes:
            "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
        }
      ]
    }
  ]
};

const res = {};

data.prerequisites.forEach(pre => {
  pre.facilities.forEach(fac => {
    res[fac.facility_id] =
      fac.facility_id in res
        ? {
            ...res[fac.facility_id],
            type: [...res[fac.facility_id].type, pre.preq_type]
          }
        : { facility_id: fac.facility_id, type: [pre.preq_type] };
  });
});

data.workComponents.forEach(work => {
  work.facilities.forEach(fac => {
    res[fac.facility_id] =
      fac.facility_id in res
        ? {
            ...res[fac.facility_id],
            type: [...res[fac.facility_id].type, work.wc_type]
          }
        : { facility_id: fac.facility_id, type: [work.wc_type] };
  });
});

const required_data = Object.values(res);

console.log(required_data);


text:
Q: matplotlib.pyplot, error in scatter function using axis (working in Jupyter Notebooks)
So, when I use the code below, I'm able to plot the surface with no errors:
# batch gradient descent setup
xInitialValue = 1.8
yInitialValue = 1.0
xyValuesArray = gradientDescent(xInitialValue, yInitialValue, xPartialDerivative, yPartialDerivative)

# plot gradient descent algorithm

# fig is a figure object (container) that holds data to represent the chart
fig = pyplot.figure(figsize = [15, 10])

# axis is a variable that holds the axis for 3D representation
# gca = get current axis
# axis -> x, y and z
axis = fig.gca(projection = '3d')
axis.plot_surface(xAxisValues,
                  yAxisValues,
                  costFunction(xAxisValues, yAxisValues),
                  cmap = colorMap.coolwarm,
                  alpha = 0.4)

# set the axis labels
axis.set_xlabel('x', fontsize = 21)
axis.set_ylabel('y', fontsize = 21)
axis.set_zlabel('z = costFunction(x, y)', fontsize = 21)

# show
pyplot.show()

However, when I try to plot some points in the same chart, I get an error:
# batch gradient descent setup
xInitialValue = 1.8
yInitialValue = 1.0
xyValuesArray = gradientDescent(xInitialValue, yInitialValue, xPartialDerivative, yPartialDerivative)

# plot gradient descent algorithm

# fig is a figure object (container) that holds data to represent the chart
fig = pyplot.figure(figsize = [15, 10])

# axis is a variable that holds the axis for 3D representation
# gca = get current axis
# axis -> x, y and z
axis = fig.gca(projection = '3d')
axis.plot_surface(xAxisValues,
                  yAxisValues,
                  costFunction(xAxisValues, yAxisValues),
                  cmap = colorMap.coolwarm,
                  alpha = 0.4)
axis.scatter(xyValuesArray[:, 0],
             xyValuesArray[:, 1],
             costFunction(xyValuesArray[:, 0], xyValuesArray[:, 1]),
             s=50,
             color='red')

# set the axis labels
axis.set_xlabel('x', fontsize = 21)
axis.set_ylabel('y', fontsize = 21)
axis.set_zlabel('z = costFunction(x, y)', fontsize = 21)

# show
pyplot.show()

The error being the following:
ValueError: Invalid RGBA argument: masked_array(data=[1.0, 0.0, 0.0, 1.0],
             mask=False,
       fill_value='?',
            dtype=object)

<Figure size 1080x720 with 1 Axes>

What am I doing wrong?
Thank you in advance!
If more context is needed I'd be happy to provide it :)

A: After doing some more digging in Stack Overflow I came across an answer that solved my problem, in this link.
Apparently, there is a problem in my environment (Ubuntu 18.04), making the data types, floats, inside my xyValuesArray different from the values returned from my costFunction (they end up being different types of floats).
xyValuesArray is a numpy.array, and the values inside of it are calculated through sympy, using diff() and then evalf(). The costFunction returns "normal" python data. I've added those modules to the tag, as the problem may reside there; if someone has a better explanation of the problem, I'd love to read it :)
If I add the following lines of code, making the float data type the same in the three different lists, then all is okay in the world:
# format data, so that the data type inside all three different is the same
x = [float(i) for i in xyValuesArray[:, 0]]
y = [float(i) for i in xyValuesArray[:, 1]]
z = [float(i) for i in costFunction(xyValuesArray[:, 0], xyValuesArray[:, 1])]

# scatter function
axis.scatter(x, y, z, s=50, color='red')

My amazing chart:


text:
Q: Wordpress check if theme is a child using stylesheet I want to check if specific theme is a child theme using stylesheet.
For exmaple:
$childBoolean = functionHere( 'twentyfifteen' );

I need some kind of function that checks if specific theme is a child. It should return a boolean.
So, is there a function that ckecks it ? Any ideas ?
Thank you

A: You can use is_child_theme() to check if the current theme is a child of another. The function documentations is here: https://codex.wordpress.org/Function_Reference/is_child_theme

A: This code might be useful if you know how to use it:
1486                    // Look in a parent theme first, that way child theme CSS overrides.
1487                    if ( is_child_theme() ) {
1488                            $template_uri = get_template_directory_uri();
1489                            **$template_dir = get_template_directory();**
1490
1491                            foreach ( $editor_styles as $key => $file ) {
1492                                    if ( $file && file_exists( "$template_dir/$file" ) ) {
1493                                            $stylesheets[] = "$template_uri/$file";
1494                                    }
1495                            }
1496                    }

(from: wp-includes/theme.php, via link in AllysonSouza's comment.
I imagine you should be able to get the template directory name using some of those php commands or pulling the variable, which is almost always the theme name.
$template_dir or get_template_directory();
Also, the following could probably be used:
128 /**
129  * Whether a child theme is in use.
130  *
131  * @since 3.0.0
132  *
133  * @return bool true if a child theme is in use, false otherwise.
134  **/
135 function is_child_theme() {
136         return ( **TEMPLATEPATH** !== STYLESHEETPATH );
137 }

The pertinent variable(?) being TEMPLATEPATH I imagine.


text:
Q: substituting values with a sql join I have two selects that I want to combine (SetA and SetB). However, for any values that are in both SetA and SetB, I only want to end up with the values from SetB. Is there a type of join I can use for this?

A: Presumably, you mean "table" not "set".  Your question is vague, but you can structure it as a query:
select b.*
from setB b
union all
select a.*
from setA a
where not exists (select 1 from setB b where b.col = a.col);

A: select a.column1, a.column2, b.column1, b.column2
from tableA as a, tableB as b
where a.column1 = b.column1

or
select a.column1, a.column2, b.column1, b.column2
from tableA as a
inner join tableB as b on a.column1 = b.column1


text:
Q: SPARQL: How to retrieve all dog breeds and all their infobox data from dbpedia? I would like to know how is the best sparql way to retrieve all dog breeds and all their infobox data from dbpedia.
I've tried this:
SELECT * WHERE {
{
  <http://dbpedia.org/resource/Dog_type> ?p ?o
}
UNION
{
  ?s ?p <http://dbpedia.org/resource/Dog_type> .
  ?s ?p ?o .
  ?p ?p2 ?o2
}
}

But the result is far away from I expect like:
http://dbpedia.org/resource/Basque_Shepherd_Dog dbpedia2:coat "moderately long"^^rdf:langString

A: First, note that <http://dbpedia.org/resource/Dog_type> is not the class of dog breeds.
For several reasons, I suggest you do this work on DBpedia Live, rather than DBpedia [Snapshot].
Start there with a look at the description of your example breed, http://dbpedia.org/resource/Basque_Shepherd_Dog.
Then consider whether a query like the following will get you what you want --
SELECT DISTINCT *
WHERE
 {
   ?breed a  <http://dbpedia.org/class/yago/DogBreeds> ;
          ?p ?o
 }
ORDER BY ?breed ?p ?o
LIMIT 1000


text:
Q: PHP: store warnings into log file without creating a personal set_error_handler Do you have any idea - if it's possibile - how to store warnings within a log file exactly as it happens for fatal errors?
Ex. code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL | E_STRICT);

[...]
error_log($try = buildLog(), 3, "errors_log/php_errors.log");
[...]

function buildLog() {
    // Get time of request
    if( ($time = $_SERVER['REQUEST_TIME']) == '') {
       $time = time();
    }
 // Get IP address
    if( ($remote_addr = $_SERVER['REMOTE_ADDR']) == '') {
       $remote_addr = "REMOTE_ADDR_UNKNOWN";
    }
 // Get requested script
    if( ($request_uri = $_SERVER['REQUEST_URI']) == '') {
       $request_uri = "REQUEST_URI_UNKNOWN";
    }

    echo "************** CHECK ***************";
    $errMy = error_get_last();
    $debug = print_r($errMy, TRUE);
    echo "
".$debug;
    echo "************** CHECK ***************";

    // Format the date and time
    $date = date("Y-m-d H:i:s", $time);

    $message = "\n"."Here is problem: $debug"."\n"."$date - $remote_addr - $request_uri "."\n";

    return $message;
 };
 [...]

In this case, for ex., I've received these logs:
 Here is problem: Array
 (
[type] => 2 [message] => Missing argument 1 for buildLog(), called in /.../file.php on line 45 and defined
[file] => /.../file.php
[line] => 729
 ) - 2016-02-01 01:09:39 - 93.40.189.183 /.../file.php

because I had a fatal error, but I'm not able to get this:
 Warning:
 fopen(http://.../file.php) [function.fopen]: failed to open stream: HTTP request failed!
 HTTP/1.0 404 Not Found in /.../file.php on line 78

that is a warning I receive running page because of:
 ini_set('display_errors', 1);
 ini_set('display_startup_errors', 1);
 error_reporting(E_ALL | E_STRICT);

UPDATE v. 0.1
Testing your suggestion I'm finding a strain behavior.
Here is code:
 [...]
 error_reporting(0);

 $url = "http://.../test.php";
 echo "
";
 print_r($url);
 $child1j10 = fopen($url, 'r');
 if ($child1j10 == FALSE) {
    echo ("
ERROR: couldn't get file, so I'll retry"."\n"."".$url."\n"."".fopen($url, 'r'));
    $errMy2 = error_get_last();
    $debug2 = print_r($errMy2, TRUE);
    echo "
".$debug2;
 };
    echo_flush();

This show me a correct warning signal even with error_reporting(0) and more precisely:
 ERROR: couldn't get file, so I'll retry  http:/.../test.php

 Array ( [type] => 2 [message] => fopen(http:/.../test.php) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found [file] => /.../test.php [line] => 80)

But if I use error_get_last() later in my code in oder to obtain writing in log file, it doesn't work.
My next part of code is:
 error_log($prova = buildLog(), 3, "errors_log/php_errors.log");
 //BUILD LOG MESSAGE
 function buildLog(){
 [... get all data...]
 echo "************** CHECK ***************";
 $errMy = error_get_last();
 $debug = print_r($errMy, TRUE);
 //echo "
".$debug;
 echo "************** CHECK ***************";

 // Format the date and time
 $date = date("Y-m-d H:i:s", $time);

 $message = "\n"."Here is problem: $debug"."\n"."$date - $remote_addr - $request_uri "."\n";

 return $message;
 };

and the log reports only:
 Here is problem:
 2016-02-01 02:45:55 - 93.40.189.183 - /.../test.php

when between "problem" and "data" there should be the array produced from error_get_last()
thx again.
UPDATE v.1 - SOLUTION
Here we go.
Sorry for your lost time, I feel a little stupid.
The problem was that I have to put function call later in code and not at the beginning as I thought (I thought it was somehow like a "server" code).
This part:
 error_log($test = buildLog(), 3, "errors_log/php_errors.log");

In this way I was able to obtain all reports inside log file.

A: You have to use built-in function trigger_error:

Used to trigger a user error condition, it can be used in conjunction with the built-in error handler, or with a user defined function that has been set as the new error handler (set_error_handler()).
This function is useful when you need to generate a particular response to an exception at runtime.

Edit:
To also save the text to standard error log, you can use error_log. Note that the message is can be sent to different targets, depending of system and/or server configuration.


text:
Q: c# Constraint: void Do(Action action) where action : static? So I want to Serialize a list of Action<T> (or otherwise strongly-typed delegates or Tasks). I've found several links that provide some insight to serializing Anonymous Delegates and using BinaryFormatter to serialize an Action<T>, but I found that this only works if the Action<T>'s are marked static, or if their Declaring Type's are marked Serializable, and I serialize those declaring objects instead. I don't need object state for anything, just the reference to a static method, so...
How do I constrain Action<T> to only where Action<T> : static?


text:
Q: When Does Lead-Free Matter? When shopping for components it's common to find a lead-free or RoHS-compliant version of the part along side one that is not. Under what circumstances does it matter that I chose exclusively lead-free or RoHS (or whatever other lead-free designation is out there) parts? What would motivate me to pick a lead-free part over a cheaper non-lead free part?
On a side note, some explanation of what all this lead-free business is about would be interesting to me.

A: These are the substances prohibited by the RoHS legislation (copied from the UK Government leaflet):
RoHS restricts the use of mercury, lead, hexavalent chromium, cadmium and a range of flame retardants notably polybrominated biphenyls and polybrominated diphenyl ethers.

A: As others have already pointed out, RoHS requirements generally forbids the use of components with hazardous materials (with some exceptions made for batteries and other specialty components where alternatives do not exist).
As a manufacturer of your product, you'll need to certify your product is RoHS compliant (amongst many other regulatory and industry requirements like emissions, safety, recyclability) in order to satisfy your customers and (in increasing number of markets) to be legally sold.  Because of this, the entire "supply chain" from the components, to the printed circuit board, to the board assembly (i.e. soldering) will need to be documented as being RoHS.
Not being "RoHS" doesn't necessarily mean that the item contains a hazardous substance.  Sometimes, the products are given the RoHS designation to confirm their process compatibility with no-lead manufacturing.  Because lead-free solder has a higher melting point, the components must also withstand higher temperatures during board assembly.

A: Aside from the RoHS stuff mentioned, in our lab we use lead free solder for high temperature circuit work, we tend to operate diodes and JFETs up to around 450degC and we've found leaded solder can't take the heat. Of course without the lead the solder is harder to work with but the result is that we can test circuits at high temperature without having to make mechanical joins between components, which is the alternative.
Oh, and although you can't use leaded solder in Europe for commercial products you can in military stuff - I think the theory is that military people don't tend to lick circuit boards but there is always the risk that a toddler will in consumer stuff :-)

A: RoHS (Restriction of Hazardous Substances Directive) covers a number of hazardous substances, not just lead. Google RoHS for a list.
You can not sell an electronic product in Europe if it contains any of the listed toxins. It seems likely that other parts of the world will follow suit.
The main challenge with RoHS is that you can not use solder that contains lead. Lead-free solder has a higher melting point and is generally a bit more tricky to work with.
On the bright side, you are less likely to cause lead poisoning to yourself or anyone else manufacturing or recycling your product :-)

EDIT: The general idea is that these toxins tend to concentrate in places like landfills. Sooner or later this stuff returns to bite you through fires, leaks etc.

The RoHS directive is not an absolute ban, it specifies the max concentration. You can for example have 0.1% lead in your product. Industrial products may not require RoHS compliance, you can for example use NiCd batteries in medical equipment even if it is banned for consumer use. But the batteries have to be brought in to recycling stations after use.
As an individual you are welcome to lick lead all day long or to import non-compliant products for your own use. You can use solder containing lead as long as you don't sell what you make.


text:
Q: Cassandra: Unknown/dynamic filters on a table, like a "feed" of tweets from an unbounded number of people I get/understand the concept of creating tables to satisfy a specific query.
But, what about queries that are dynamic?
Let's say I create a "tweet" table. I follow two users, Paul and Jim. Surely, there isn't a "tweets_by_paul_and_jim" table. So what do I do?
Do I query the results for each user query, and combine them into a sorted list for each request, AT request time? This really won't work because a user could follow 30,000+ (unbounded) number of people.
How does twitter solve this problem?

A: If you tweet a message, it's ending up in each of your followers timeline. Twitter will simply write the message to each timeline using a fanout approach. You can read more about how this used to work back a few years ago in this article.


text:
Q: iterator find method for custom class vector I want to use find method of iterator to check if an instance of class I have defined already in the vector or not. I have overloaded the == operator for the class. However, I couldn't get it to compile.
What am I missing here?
Thanks n advance.
here is a snippet from the code:
vector<ContourEdgeIndexes>::iterator it = find(contourEdges.begin(),contourEdges.end(),contourEdgeCand);
        if(it != contourEdges.end()) {
            contourEdges.erase(it);
        }

compiler gives this error:
error: no matching function for call to     'find(std::vector<ContourEdgeIndexes>::iterator, std::vector<ContourEdgeIndexes>::iterator, ContourEdgeIndexes&)'

edit:
and here is the overloaded == operator:
bool operator == (ContourEdgeIndexes& rhs) {
    if((this->first == rhs.first) && (this->second == rhs.second))
        return true;
    else
        return false;
}

A: Your operator should accept constant reference to ContourEdgeIndexes, if it defined as member. Also operator itself should be const.
bool operator == (const ContourEdgeIndexes& rhs) const {
    return ((this->first == rhs.first) && (this->second == rhs.second));
}


text:
Q: Background with two colors - React Native Is there a way to have a background with two colors as follows: Two colors
I tried expos Linear Gradient, but that's Gradient. I'm not sure how to put two colors in the main View tag as background ?
Any suggestions?

A: If the dimensions of the view doesn't get you anywhere, try to manipulate its borders, for example, try this code:
import React, { Component } from 'react'
import { View, Dimensions } from 'react-native'

const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window')

class App extends Component {
    render() {
        return (
            <View style={{ flex: 1 }}>
                <View
                    width: SCREEN_WIDTH,
                    height: 0,
                    borderTopColor: "blue",
                    borderTopWidth: SCREEN_HEIGHT / 2,
                    borderRightWidth: SCREEN_WIDTH,
                    borderRightColor: 'transparent'
                />
            </View>
        )
    }
}

export default App

And it gives you:

Off Topic
I still don't understand why people dislike questions like this. Yes there's no code posted, but it doesn't mean he didn't try anything. Maybe he did, but none of the methods he tried was anywhere near the answer, then why should he post the code up here to make the question lengthy, just to prove that he did try? And, even if he didn't try much, maybe it's because he had no clue what to try, isn't that a possibility?
There are many questions without any code posted but got hundreds of upvotes, such as "How to remove an element from an array in JavaScript?". Really? I honestly think if you even read the documentation and tried some methods such as .splice, .reduce, .unshift, you would've figured that out without having to ask it here on SO. Those questions were popular because they made a lot of beginners (including me) lives easier, not because those questions showed that whoever asked it made a great amount of effort. And this question certainly is a good one in that sense. (But maybe he should change the title of the question to make it more specific, because it would benefit others when they goole it)


text:
Q: Ruby how to call a method only when the object is not nil I'm writing a simple script, that fetches the details of some packages from the debian website. I encounter a problem when dealing with virtual packages that ave no version no associated with them.
I get the following error message
undefined method `first' for nil:NilClass (NoMethodError)

The culprit line is
version = doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last.first

I tried to put it into an if conditional like this but that doesn't work.
if doc.css('#content h1').text
         version = doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last.first
      end

So I'd like to know how I can check if the object is not nil and then try to extract the sub-string from it.
Here is the entire script with the unless block added
require 'rubygems'
require 'nokogiri'
require 'open-uri'

# additional code to make sure that we can resume after a break seamlessly
last_package = 0
File.open('lastbreak','r') { |fptr| last_package = fptr.gets.to_i }
puts "Resuming from package:#{last_package}" if last_package != 0

# to read each package from packageslist.txt and fetch the required info
# also to store this into a file that can easily be read by the c++ program
BASE_URL = "http://packages.debian.org/stable/"

File.open('packages_list.txt','r') do | fptr |
  while line = fptr.gets
    package_id = line.split[0].to_i
    package = line.split[1]
    dependencies = ""
    url = BASE_URL + package
    if package_id >= last_package
      doc = doc = Nokogiri::HTML(open(url))
      doc.css(".uldep a").each do |dependency|
        dependencies << dependency.text + ","
      end
      dependencies = dependencies.split(',').uniq.join(',')
      description = doc.css('#pdesc').text.strip
      version = ""
      unless doc.css('#content h1').nil?
          version = doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last.first
      end

      File.open("packages/#{package}","w") do |wfptr|
      wfptr.puts "PackageId:#{package_id}"
      wfptr.puts "Name:#{package}"
      wfptr.puts "Version:#{version}"
      wfptr.puts "Deps:#{dependencies}"
      end
      File.open("packages/#{package}.description",'w') {|wf| wf.write(description.capitalize)}

      package_id += 1
      puts "Now Processing #{package_id}"
      File.open('lastbreak','w') { |fptr| fptr.puts "#{package_id}" }
    end
  end
end

now the error message is
/Users/ccuser008/Documents/oops_project/repo/repobuilder.rb:30:in `block': undefined method `first' for nil:NilClass (NoMethodError)
    from /Users/ccuser008/Documents/oops_project/repo/repobuilder.rb:15:in `<main>'

A: Depends what is being returned nil doc.css('#content h1') or doc.css('#content h1').text or doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last
Example -
unless doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last.nil?
    version = doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last.first
end

you can include the proper condition in the unless clause.
From your exception doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last seems to be nil. So you can check on this.

A: Have you used try?
Something like
doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last.try(:first)

This will work if you're including active_support in your project or if you are working in a Rails app.
Lookup the syntax and documentation of the "try" method.
Updated:
x = doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last
version = x.first if !x.nil? # why bother.

Just FYI: I know this doesnt really apply to your question, but perhaps chaining methods this long without checks for null in between is probably coupling very very hard to the input's document structure. What if .css("#content h1").text is null?

A: Ruby 2.3.0 added a safe navigation operator (&.) that checks for nil before calling a method.
foo&.bar

It will return nil if foo is nil, rather than raising NoMethodError.

A: Use
try(method, *args, &block)

in your case:
doc.css('#content h1').text.strip.scan( /\(([^>]*)\)/).last.try(:first)

For more info see:
http://www.intridea.com/blog/2010/11/2/calling-methods-on-potential-nil-objects-in-rails


text:
Q: detect duplicate but ignore a value on PHP array I know how to detect duplicate value in PHP array by using array_diff_key( $x , array_unique( $x ) );.
My problem is I want to detect duplicate value in PHP array, but ignore a value or NULL value. For example:
$x = array (1,0,0,0,4,4,3);
$x = array (1,NULL,NULL,NULL,4,4,3);

I want to detect 4 without changing the array structure (array length must still 7).
Is this possible in PHP ? How to do that?

A: Try this:
$y = array_filter($x,function($d){return $x!==null;});
$z = array_diff_key($y,array_unique($y));

$y has only the items NOT null.
$z has the keys of the duplicate items from $x that are not null.

A: I could do the following custom function detectArr:
<?php
$x = array (1,0,0,0,4,4,3);

    function detectArr($arr){
       $output = array();
       foreach ($arr as $i){
            if ($i){
                    $output[] = $i;
            }
            else{
                    $output[] = NULL;
            }
       }
        return $output;
    }

    echo "<pre>";
    print_r(detectArr($x));

Checkout this DEMO: http://codepad.org/W8ocL6dj


text:
Q: Where to insert this snippet in functions.php file of WordPress child theme The entire functions.php file in my child theme currently is:
<?php
   add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
   function theme_enqueue_styles() {
     wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
     wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style-rtl.css' );
   }
 ?>

<?php
  // Display 6 products per page. Goes in functions.php
  add_filter( 'loop_shop_per_page', create_function( '$cols', 'return 6;' ), 20 );
?>

I need to add a snippet to change the footer. I got this snippet from WordPress support, but every place I insert it I get a syntax error. I've inserted it multiple ways, properly nested in tags, but my site always breaks. Could a kind person please show me how the entire functions.php files should look, after I insert this snippet?
add_action( 'init', 'custom_remove_footer_credit', 10 );

function custom_remove_footer_credit () {
  remove_action( 'storefront_footer', 'storefront_credit', 20 );
  add_action( 'storefront_footer', 'custom_storefront_credit', 20 );
}

function custom_storefront_credit() {
?>
  <div class="site-info">
     © <?php echo get_bloginfo( 'name' ) . ' ' . get_the_date( 'Y' ); ?>
  </div><!-- .site-info -->
<?php
}
?>


text:
Q: Cannot access private member in class sf::NonCopyable. Where is the copy? C++ Using SFML 2.1
I decided to make an object that contains my audio files. However, when I run my test, I get the following error:
error C2248: 'sf::NonCopyable::NonCopyable' : cannot access private member declared in class 'sf::NonCopyable'
I looked up some information about this error on the SFML website and it states that I am not able to copy an object that inherits sf::NonCopyable (I think). These objects are probably sf::Sound and sf::Music as I am about to show. The real question is: where is this copy made and how do I fix it?
Audio class
struct Audio {
    std::map<std::string, sf::Sound> sounds;
    std::map<std::string, sf::Music> musics;

    Audio() : sounds(),
        musics(){}

    void addSound(sf::Sound& s, sf::SoundBuffer& sb, std::string key){
        s.setBuffer(sb);
        sounds.insert(std::pair<std::string, sf::Sound>(key, s));
    }
    void addSound(sf::Sound& s, std::string key){
        sounds.insert(std::pair<std::string, sf::Sound>(key, s));
    }
    void addMusic(sf::Music& m, std::string key){
        musics.insert(std::pair<std::string, sf::Music>(key, m));
    }
    sf::Sound& getSound(std::string key){
        return sounds[key];
    }
    sf::Music& getMusic(std::string key){
        return musics[key];
    }
};

Load Sounds method
void loadSounds(Audio& audio){
    sf::Music backgroundMusic;
    sf::Sound eating;
    sf::SoundBuffer sb_eating;
    sf::Sound moving;
    sf::SoundBuffer sb_moving;
    sf::Sound losing;
    sf::SoundBuffer sb_losing;
    sf::Sound begin;
    sf::SoundBuffer sb_begin;

    if (!backgroundMusic.openFromFile("backgroundmusic.wav"))
        std::cerr << "Error opening \"backgroundmusic.wav\"" << std::endl;
    if (!sb_eating.loadFromFile("eatingsfx.wav"))
        std::cerr << "Error opening \"eatingsfx.wav\"" << std::endl;
    if (!sb_moving.loadFromFile("movingsfx.wav"))
        std::cerr << "Error opening \"movingsfx.wav\"" << std::endl;
    if (!sb_losing.loadFromFile("losingsfx.wav"))
        std::cerr << "Error opening \"losingsfx.wav\"" << std::endl;
    if (!sb_begin.loadFromFile("beginsfx.wav"))
        std::cerr << "Error opening \"beginsfx.wav\"" << std::endl;

    eating.setBuffer(sb_eating);
    moving.setBuffer(sb_moving);
    losing.setBuffer(sb_losing);
    begin.setBuffer(sb_begin);

    audio.addMusic(backgroundMusic, std::string("backgroundMusic"));
    audio.addSound(eating, std::string("eating"));
    audio.addSound(moving, std::string("moving"));
    audio.addSound(losing, std::string("losing"));
    audio.addSound(begin, std::string("begin"));
}

Main Method
int main(){
    /*Initialize the objects*/
    Snake snake = Snake();
    Audio& audios = Audio();
    sf::Text textCount;
    Apple apple(0, 0);
    apple.locateApple();
    sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "SFML Application" );
    /*Load the audio*/
    loadSounds(audios);

    audios.getMusic("backgroundMusic").setVolume(10);
    audios.getMusic("backgroundMusic").setLoop(true);
    audios.getMusic("backgroundMusic").setVolume(25);

    /*Load the font*/
    sf::Font font;
    if (!(font.loadFromFile("arial.ttf")))
        std::cout << "Error loading fonts" << std::endl;
    /*Create the text*/
    textCount.setFont(font);
    textCount.setString(std::string("points: ") + std::to_string(points));
    textCount.setColor(sf::Color::Red);
    textCount.setCharacterSize(20);
    textCount.setPosition(windowWidth / 2 - (textCount.getString().getSize()*(textCount.getCharacterSize() / 5)), textCount.getCharacterSize() - 5);
    textCount.setStyle(sf::Text::Bold);

    window.draw(textCount);

    /*Set Framerate fps*/
    window.setFramerateLimit(10);

    /*MAIN GAME LOOP*/
    counterTick = 1;

    audios.getSound("begin").play();
    audios.getMusic("backgroundMusic").play();
    while (inGame)
    {
        std::string counter = std::to_string(counterTick);
        std::cout << "Tick: " + counter << std::endl;

        window.clear(sf::Color::Black);
        sf::Event event;
        while (window.pollEvent(event)){
            if (event.type == sf::Event::Closed)
                window.close();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) break;
        /*Call Updates*/
        snake.input();
        snake.checkReals();
        snake.moveUpdate();
        audios.getSound("moving").play();

        /*Call Collisions*/
        std::cout << "     Outside Collision Loop " << std::endl;
        checkApple(snake, apple, audios.getSound("eating"));
        checkBoundary(snake);

        /*Call Draw*/
        std::vector<sf::RectangleShape> shapearray = snake.draw();
        for (int i = shapearray.size() - 1; i >= 0; i--){
            window.draw(shapearray[i]);
        }
        window.draw(textCount);
        window.draw(apple.draw());
        window.display();

        counterTick++;

    }
    audios.getSound("losing").play();
    audios.getMusic("backgroundMusic").stop();
    std::system("PAUSE");//bad practice, debuggin purposes
    return 0;
}

A: Like the comments already mentioned, sf::Music can't be copied. Your best bet is to probably just wrap it inside a std::unique_ptr since you don't need to share ownership.
Since you said in earlier Questions that you are doing this for school I'm going to show you how to do this in general with C++11
#include <string>
#include <map>
#include <memory>

//non copyable and non movable like sf::Music
struct NonCopyable
{
    NonCopyable() {};
    NonCopyable(const NonCopyable &&other) = delete;
    NonCopyable(const NonCopyable &other) = delete;
    void randomFunc(){}
};

struct MapHolder
{
    std::map<std::string, std::unique_ptr<NonCopyable>> container;

    void addElement(const std::string &key, std::unique_ptr<NonCopyable> value)
    {
        //std::move is necessary here, compiler error without it, since
        //unique_ptr<T> is non-copyable but can be moved just fine
        container.insert({key , std::move(value)});
    }

    NonCopyable &get(const std::string &key)
    {
        //using container[key] will create a new NonCopyable if none is found
        //this will however throw an exception if key is not in the map
        return *container.at(key);
    }

    //probably not necessary in this case but this is so that you can get a
    //const NonCopyable elements from a "const MapHolder", without this,
    //calling ".get" on a "const MapHolder" would be an error
    const NonCopyable &get(const std::string &key) const
    {
        return *container.at(key);
    }

};

int main()
{
    MapHolder holder;

    auto myInstance = std::make_unique<NonCopyable>();
    //if make_unique is not supported on your compiler use this:
    //auto myInstance = std::unique_ptr<NonCopyable>(new NonCopyable());

    //this is how you access members of NonCopyable
    myInstance->randomFunc();

    //again, the move here is necessary, since std::unique_ptr is non-copyable
    //after this line "myInstance" is invalid
    holder.addElement("test", std::move(myInstance));

    //doing this is illegal now, since myInstance is now moved
    //it should be noted that std::move was only a cast, the actual moving
    //happened because "addElement" took the unique_ptr by value and
    //thereby transferred the ownership during construction of its local parameter
    //myInstance->randomFunc();

    //this is ok
    holder.get("test").randomFunc();

    //this is fine too
    NonCopyable &local_ref = holder.get("test");
    local_ref.randomFunc();

    return(0);
}


text:
Q: Libxml cross compile for embedded system I am trying to figure how to compile libxml2 library for my embedded system, which is powerpc architecture and has no os (bare metal). It seems like I need to execute configure file and set CC flag to something I do not know what. Thanks for help!

A: CC is the executable of your C compiler.  It could be something like powerpc-linux-gcc, but really that really depends on your cross compilation environment.


text: Q: word mail merge - importing data from excel to word checkbox/drop down fields I have a word form with checkboxes and drop down list…is there a way to import data from a excel spreadsheet…we plan on sending these out and need the fields in end product to be active so clients can change anything that is wrong (choose the right answer from the drop down list, check or uncheck boxes)


text:
Q: Puzzle: leaning a ladder at $45^\circ$ to a wall using only yourself This question was asked to my friend in an interview.
You are provided a ladder and are led to  a wall. The ladder must be kept against the wall making an angle of $45^\circ$ with the floor. You are given no measuring instruments whatsoever. All you have is yourself and the ladder.Nothing else. You are not given the value of the ladder's length or anything else of that sort.
How will you go about doing it?
If you think this involves physics rather than just math, please do mention if I must move the question elsewhere. And in case you're thinking, the interviewer has measuring instruments and will check your work after you're done.An exact value of $45^\circ$ is expected. And I am not sure if "not possible" or "insufficient data" is an accepted answer.
I really don't know what tags to use for this. I request you to edit my question with the appropriate tags.

A: *

*Stand the ladder up vertically against the wall.

*Now lie straight on your front on the ground perpendicular to the wall (it shouldn't matter if you aren't perpendicular) with your arms outstretched above your head and touching the feet of the ladder with your hands.

*Keeping your feet in the same position, stand up straight.

*rock the ladder towards you, keeping its feet in the same place until you are holding it by the sides (rungs are not guaranteed to be available) with your arms outstretched directly above your head

*Somehow pick the ladder up, walk away from the wall and turn around so that the ladder is standing on its feet with its end suspended in the air but not touching the wall. You should be between the feet of the ladder and the wall

*Walk (perpendicular to the wall) towards the wall, allowing the ladder to slide along the ground, pivoting about your hands until it touches the wall.

*By similar triangles, the ladder is now touching the wall.

A: Assuming you have some kind of marking device (chalk, or the like):
If the ladder is telescoping (building on my answer in the comments), you could stand the ladder vertically and horizontally at the foot of the wall, mark the endpoints on the floor and the wall, then extend the ladder until it was just sufficient to meet those two marks.
If it's just an ordinary single-length ladder, pick two points $A, B$ at the foot of the wall, closer together than half the length of the ladder.  Use the ladder as a rusty compass to construct the perpendicular bisector of $\overline{AB}$ that meets the wall at $C$, and is one ladder length distant from the wall at $D$.  Then draw a circular arc, centered at $C$, from $D$ to the wall.  Construct the bisector of that arc at $E$.  Place one end of the ladder at $E$ and let it fall against the wall.  It will be at a $45$-degree angle (for ideal ladders and walls, but this is an imaginary problem, anyway).

A: Why not use yourself as the measuring device? (If you know your exact height, which is mostly the case, that's perfect!). Measure the ladder length as $x$ units of your height. Now you know that when the ladder is up against the wall, the base and the altitude formed by the ladder (with its own length as the hypotnuse of the supposed triangle) are equal to $x \cdot cos(\theta)$. Just incline the ladder such that the base is equal to what you calculated. The method is prone to errors of measurement but given it is an interview question and the fact that what I said is logically correct, you ace the interview. :)


text:
Q: sanitize html jquery-ui php input variables for oracle querys I just get a lil (xD, a lot would be better) worried about sanitizing input variables when using 'em in SQL querys.
I had read a lot in here and other webs but, they all talk about mysql_real_escape_string()
I would like some help learning to do something like that, but I'm using Oracle 10g. Also I'm using jquery to do some validation.
So I'd like to know ways to protect me working the client side.
I'm willing (like always) to read anything that would help, my problem is I don't know where to start.

A: Use Bind Variables that way you don't even have to worry about it. I'm no php programmer, but a quick google of oracle php bind variable yields some good results, like this one: http://php.net/manual/en/function.oci-bind-by-name.php
Bind Variables ensure that you are immune to sql injection attacks, as well as vastly improve the performance of your query in oracle (they allow oracle to cache the "soft parsed" query).


text:
Q: Can I snooze notifications from the browser on High Sierra? Calendar notifications shows a Snooze button. But notifications from browsers do not.
Is there any way to enable snooze on Browser's notifications too?

A: Safari doesn't give you the option to exactly "snooze" website notifications (because the snooze feature is Siri suggested with that notification), but you can manage them:

*

*Stop receiving notifications from a website: Choose Safari > Preferences, click Websites, then click Notifications. Find the website in the list, then select Deny.

*Change how website notifications appear: Choose Apple menu > System Preferences, click Notifications, select the website on the left, then change the notification alert style and other settings on the right.

*Stop seeing notification permission requests in Safari: Choose Safari > Preferences, click Websites, then click Notifications. Deselect "Allow websites to ask for permission to send push notifications." From now on, when you visit a website that can send you notifications, you aren't asked.

Perhaps when MacOS Mojave goes public we will see that as an option. If not, feel free to join the beta/development team and petition your request for that feature.
In the mean time these options work best.

A: You could use Add-on for your Browsers like this one for Chrome

https://chrome.google.com/webstore/detail/notification-manager/cpjcbknbblieopkakonjnpedhmnhgggg?hl=en


text:
Q: How to solve this equation $x^5 +4^y=2013^z$ in positive integers? I think to solve the equation in positive integers. It appears in a contest and I don't remember where.
I obtain that $x$ must be an odd number and further $x=1 \, mod\, 4$.
Any hint is appreciated.


text:
Q: The best way to find index of point in nd array in python I am using Python3 and numpy. I have an nd array like:
arr = np.array([[1,2], [3,4],[5,6]])

I want to find position of point for example [3,4]. I am using this
idP = [id for id in range(len(arr)) if (arr[id] == [3,4]).all()]

what is the best way to do this

A: You can do it by:
(arr == [3, 4]).all(-1).nonzero()[0]

or by using np.isin:
np.isin(arr, [3, 4]).all(1).nonzero()[0]

A: How about this?
arr.tolist().index([3,4])

A: One solution could be converting you numpy array into a python list
arr.tolist().index([3,4])
>>> 1


text:
Q: Representing unlimited in database with integer data type I have a table that saves some account limits like users. For most rows this value will be an integer. However I will also need to support storing unlimited (infinite) as a value. This might seem silly but is there a common integer value that represents unlimited (infinite)? I'd like to keep storing the values as integers.

A: You can't really have an infinite number of accounts since there aren't an infinite number of people.  In fact, you really are limited in the number of accounts that you can have (if you choose to store the value in a single database column) since any finite storage mechanism for countable things has a limit.  I'd suggest, with @Tor Haugen, that the best way to do this is to use the limit imposed by the system (whatever maximum integer or long your language provides).  That way you won't have to worry about any special cases for your comparisons.  Additionally, I'd use a database constraint to prevent storing negative values in the field.  A 64-bit integer will certainly hold a number big enough to be practically unlimited for your application.

A: Well, if you're accessing your database from .NET, the integer types have constant members MaxValue and MinValue. We sometimes use them to represent infinity. Of course, these values have no special meaning in your RDBMS...

A: *

*use zero

*use -1

*use null

I prefer null, unless the field is not nullable, then I prefer zero, unless zero is a valid limit, then I prefer -1, unless -1 is a valid value, in which case you need another field (say, a bit field) to signify 'unlimited'.

A: As an integer, infinity will be hard.  A few options:
1)  -1, with corresponding program logic that treats it as infinite (and assuming that negative values aren't actually valid).
2)  An extra column holding a flag indicating finite/infinite.

A: I don't think there's a perfect solution. So here goes my suggestion:
Create constants that represent the max values that can be stored in your database and consider them as "Infinity".
http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html#integer-types


text:
Q: GNU Screen - any way to remove password when detached? Protecting a GNU screen session with a password is good security.  However, how does one remove the password if you need to share a session with a colleague?
I tried the following to clear it and got locked out (I ought to have tested it before detaching, but...):
ctrl+a :password clear

So, what exactly is the password set to in the above scenario?  Neither my previously set password nor my system account password would let me back in!

A: From man screen:

password [crypted_pw]
Present a crypted password in your ".screenrc" file and screen will ask for it, whenever someone attempts to resume a detached. This
  is useful if you have privileged programs
         running  under  screen  and  you want to protect your session from reattach attempts by another user masquerading as your uid (i.e.
  any superuser.)  If no crypted password is
         specified, screen prompts twice for typing a password and places its encryption in the paste buffer.  Default is `none', this
  disables password checking.

ctrl+a :password none should do what you want.


text:
Q: Entity Framework Batch Update by ID I'm using an Entity Framework project in which I need to batch update records by ID. The ID (i.e. the primary key of a particular table) is available at runtime, and I would like to update all records like in the following query:
UPDATE EntityTable
SET Column = @p0
WHERE EntityID IN '1,2,3,[...]'

The problem I'm running into is that I have around 60k IDs (at worst) that I will need to handle, and our database software (SQL Server 2008) can't handle this:

The query processor ran out of internal resources and could not
  produce a query plan. This is a rare event and only expected for
  extremely complex queries or queries that reference a very large
  number of tables or partitions. Please simplify the query. If you
  believe you have received this message in error, contact Customer
  Support Services for more information.

Through Google searches I've found people using old-school DataTable and SqlDataAdapter calls to accomplish this, but I'd like to stay within the spirit of Entity Framework if possible, or raw sql if necessary. Is there any way to do this in a reasonably efficient manner?

A: EF doesn't directly support batch updates so you have to use direct SQL. Your best choice is stored procedure with table valued parameter containing your IDs. EF doesn't support table valued parameters and because of that you have to use ADO.NET directly.
Your current solution can be improved only by dividing yours IDs into smaller groups and execute your update for each subset separately.


text:
Q: Making my GIS application OGC compliant We have a stack of open source software's which we use to build a GIS.
We would like to align our application to OGC as much as possible. I visited the site and read about the standards.
Now my question is how to start with making the application OGC compliant. There are lot of documents which talk about standards but I couldn't find much on how to get started. Specifically given that am building on top of Open Source software's and Implementing is very subjective word.
Can you guide me to some resources which can get me started?
Ideally we would like address Web Mobile and Desktop, We have a existing solution for Desktop but are planning to go ahead with Web. We are aiming for a GIS product.
Here is the list of Open Source Products: GDAL/OGR, GeoServer, OpenLayers, Cesium

A: As you have found in your research there is no how-to manual for "OGC-compliance".  OGC standards are continuously debated by the OGC, vendors, the open-source community, government, and other users and stakeholders.  Most real work ends up being implemented using non-OGC open specifications like geojson and shapefiles.
The simplest way to get started would be to implement KML import and export in your application.  Here are the reason why:
-KML is an OGC standard
-KML is relatively simple to implement
-KML is widely supported on nearly all desktop and mobile platforms (sometimes read-only) but Google is always creating new Earth clients on different platforms
-KML can represent both vector and raster formats
-KML's kmz is also easy to implement (just zip compression) to distribute a single file for an entire GIS
So if you just want to be OGC compliant for marketing purposes, KML is the shortest route.  It also buys you a good bit of true interoperability.


text:
Q: How to port android to device on ARM9 processor? I want to port Android on the device with ARM9 200Mhz and no-fpu support, Is this possible, Has google revealed all code of android or it is just available to partners?

if ANDROID_PORT_POSSIBLE
{
      Is there any tutorial available for porting?
}

Thanks and Regards,
Sunny.

A: This article might help you
http://www.linuxfordevices.com/c/a/Linux-For-Devices-Articles/Porting-Android-to-a-new-device/

A: ARMv5TE is the minimum (as said here), and some ARM9 CPUs are ARMv4. As I know you are using ARM926, which is ARMv5TE, so it's possible.
You can search google.groups - there is a lot of information. I think, you can find ready-for-compilation ARM9 sources.

A: Someone tried making the ARMv5te code run on ARMv4t CPUs by emulating the missing instructions in the kernel. In the end they were defeated but the blog describing the efforts is a technical tour-de-force!
http://benno.id.au/blog/2007/11/21/android-neo1973
Meanwhile someone else has succeeded by recompiling everything for armv4: http://wiki.openmoko.org/wiki/User:Seanmcneil3


text:
Q: VS code SAM Debugger - Error running command "sam local start-api": Timeout token cancelled When I try to run the debugger in VS CODE with SAM hello world for Python, it creates the following in lunch.json
    {
        "type": "aws-sam",
        "request": "direct-invoke",
        "name": "API ocrSam:HelloWorldFunction",
        "invokeTarget": {
            "target": "api",
            "templatePath": "${workspaceFolder}/ocrSam/template.yaml",
            "logicalId": "HelloWorldFunction"
        },
        "api": {
            "path": "/hello",
            "httpMethod": "post",
            "payload": {
                "json": {
                    "tst": "ttt"
                }
            }
        },
        "lambda": {
            "runtime": "python3.8"
        }
    }

When I run it I get:
2023-01-06 00:43:10 [INFO]: Command: (not started) [/usr/local/bin/sam local start-api --template /tmp/aws-toolkit-vscode/vsctkDR7EPj/output/template.yaml --port 5858 --debug-port 5859 --debugger-path /home/ubuntu/.vscode-server/extensions/amazonwebservices.aws-toolkit-vscode-1.60.0/resources/debugger --debug-args /var/lang/bin/python3.8 /tmp/lambci_debug_files/py_debug_wrapper.py --listen 0.0.0.0:5859 --wait-for-client --log-to-stderr /var/runtime/bootstrap.py]
2023-01-06 00:43:10 [ERROR]: Error running command "sam local start-api": Timeout token cancelled

When I copy the cmd and try to run it from CLI I get:
/usr/local/bin/sam local start-api --template /tmp/aws-toolkit-vscode/vsctkDR7EPj/output/template.yaml --port 5858 --debug-port 5859 --debugger-path /home/ubuntu/.vscode-server/extensions/amazonwebservices.aws-toolkit-vscode-1.60.0/resources/debugger --debug-args /var/lang/bin/python3.8 /tmp/lambci_debug_files/py_debug_wrapper.py --listen 0.0.0.0:5859 --wait-for-client --log-to-stderr /var/runtime/bootstrap.py

Error: No such option: --listen
How can I by-pass this issue?
NOTE: this issue happened on my old pc which was dying, I bought a new mac and it doesn't happen any more, so it might be a specific problem of the pc

A: Which sam cli version do you have installed and which OS are you using?
Can you try increasing the aws.samcli.lambdaTimeout setting in the VSCode settings to something like 90000 (1.5 minutes) to see if the default timeout is too low


text:
Q: Service method is not called when passing heavy parameter object I am working on xamarin.ios. I am consuming web service. I have added the web service reference with my project. Now I am consuming the service methods. Everything is working fine. There is a method in service in which I pass an object of data which contains the all information of data. But it works only some time. And rest time I get error of "Request Time out".
I found that if I remove some items from passing objcet to make the parameter object lighter then it works, but if I don't make it lighter I get the "Request Time out" error.
I am getting this problem only when I am trying to consum it in xamarin.ios. It is working fine in xamarin.android.
I am not able to find the actual problem. Can any one tell me if the problem is from my code or the problem is from server or service side?


text:
Q: Monogame mouse in windows 10 feels press only after move I have monogame (3.4) XAML application for windows store (VS2012 on Win10). In my game's Update() I call attched code to receive toutch events. In windows 8/8.1 everything worked, but in windows 10 I have to hold button and move mouse several times to get ButtonState.Pressed - for end user this looks like mouse doesn't work at all. How can I manage this bug?
Mouse event receive code:
        MouseState st = Mouse.GetState();
        if (st.LeftButton == ButtonState.Pressed)
        {
            if (prevMouseState == ButtonState.Released)
            {
                prevMouseValX = st.X;
                prevMouseValY = st.Y;
                pushEvent(EVT_POINTER_DOWN, (int)(st.X - mScrBiasX), (int)(st.Y - mScrBiasY), 1, 0);
            }
            else
            {
                if (Math.Abs(st.X - prevMouseValX) > 2 || Math.Abs(st.Y - prevMouseValY) > 2)
                    pushEvent(EVT_POINTER_MOVE, (int)(st.X - mScrBiasX), (int)(st.Y - mScrBiasY), 1, 0);
            }
            prevMouseState = ButtonState.Pressed;
        }
        if (st.LeftButton == ButtonState.Released)
        {
            if (prevMouseState == ButtonState.Pressed)
            {
                pushEvent(EVT_POINTER_UP, (int)(st.X - mScrBiasX), (int)(st.Y - mScrBiasY), 1, 0);
            }
            prevMouseState = ButtonState.Released;
        }

A: The answer is to use the last development version of Monogame - from sources -  (and build win 8.1 binaries using VS2013-2015)


text:
Q: Complex analysis fundamental theorem of calculus on integration Suppose f is a continuous function on an open set Ω which has an anti-derivative on
Ω.
if γ, γ' are two paths in Ω with the same beginning point and the same end point, are below statement true?
$$\int_{\gamma} f(z) \, dz =\int_{\gamma'} f(z) \, dz   $$
My approach: I think it should be the same, since it has two curves ends in the same points.
Also by the fundamental theorem of the calculus, I know that using F as derivative of f. $$\int_{\gamma} f(z) \, dz = F(\gamma(b)) - F(\gamma(a))$$
$$\int_{\gamma'} f(z) \, dz = F(\gamma'(b)) - F(\gamma'(a))$$
But I am not sure how to approach this problem to show that these are equal. I think I need to use the fact $$\int_{\gamma} f(z) \, dz = 0$$ But not sure how to prove this.

A: If $\gamma$ and $\gamma'$ have the same end points, that is, $\gamma(a) = \gamma'(a)$ and $\gamma(b) = \gamma'(b)$, then obviously $F(\gamma(a)) = F(\gamma'(a))$,$F(\gamma(b)) = F(\gamma'(b))$, so $F(\gamma(b)) - F(\gamma(a)) = F(\gamma'(b)) - F(\gamma'(a))$.


text:
Q: simple url rewriting need I need a simple redirect for my pages.
I need the following rewritten:

http://abc.de/application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/268/web/Aktivreisen-Wanderreisen.htm    http://abc.de/aktivreisen-schottland.html
http://abc.de/application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/270/web/Busrundreisen.htm http://abc.de/busrundreisen-schottland.html
http://abc.de/application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/1223/web/Ferienhotels.htm   http://abc.de/hotels-schottland.html
http://abc.de/application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/1217/web/Auto-Rundreisen.htm    http://abc.de/auto-rundreisen-schottland.html
http://abc.de/application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/1222/web/Stadthotels.htm    http://abc.de/hotels-schottland.html
http://abc.de/application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/1212/web/Unterkunftsschecks.htm http://abc.de/unterkunftsschecks-schottland.html

The problem is that /application/index.cfm does not exist and the server displays a 404 not found irrespective of how I configure  http.conf or the .htaccess file.
What should I put in my .htaccess file?

A: Based on the example above you'd need to rewrite each one individually. The reason is that there is no repeatable mapping pattern between the .htm pages and the ones you're rewriting to:

Rewrite Engine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/268/web/Aktivreisen-Wanderreisen.htm    http://abc.de/aktivreisen-schottland.html [NC,R=301]
RewriteRule application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/270/web/Busrundreisen.htm   http://abc.de/busrundreisen-schottland.html [NC,R=301]
RewriteRule application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/1223/web/Ferienhotels.htm   http://abc.de/hotels-schottland.html [NC,R=301]
RewriteRule application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/1217/web/Auto-Rundreisen.htm    http://abc.de/auto-rundreisen-schottland.html [NC,R=301]
RewriteRule application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/1222/web/Stadthotels.htm    http://abc.de/hotels-schottland.html [NC,R=301]
RewriteRule application/index.cfm/fuseaction/home.uebersicht/idLand/44/idReiseart/1212/web/Unterkunftsschecks.htm http://abc.de/unterkunftsschecks-schottland.html [NC,R=301]


text:
Q: Search and remove an element in mulit-dimentional array in php depending on a criteria I've a simple question about multi-dim array, I want to remove any redundent element let's say in my case, [serviceMethod] => PL is coming 2 times, I want to search 'PL' with respect of [APIPriceTax] if an element has a lower price I want to keep it and remove the other one in array
Array (
    [0] => Array (
                   [carrierIDs] => 150
                   [serviceMethod] => CP
                   [APIPriceTax] =>  30.63
                   [APIPriceWithOutTax]  28.32
                   [APIServiceName] =>  Xpresspost USA
                   [APIExpectedTransitDay]  => 2
               )
    [1] => Array (
                    [carrierIDs] => 155
                    [serviceMethod] => PL
                    [APIPriceTax] => 84.13
                    [APIPriceWithOutTax] => 73.8
                    [APIServiceName] => PurolatorExpressU.S.
                    [APIExpectedTransitDay] => 1
               )
  [2] => Array (
                    [carrierIDs] => 164
                    [serviceMethod] => PL
                    [APIPriceTax] => 25.48
                    [APIPriceWithOutTax] => 22.35
                    [APIServiceName] => PurolatorGroundU.S.
                    [APIExpectedTransitDay] => 3
                  )

)
This is my pseudo code: Where $carrierAddedToList is the actual array
$newCarrierAry = function($carrierAddedToList)
  {
   $newArray = array();
   foreach($carrierAddedToList as $cV => $cK)
   {
    if( !in_array($cK['serviceMethod'],$newArray) )
     {
       array_push($newArray, $cK['serviceMethod']);
     }

   }
    return $newArray;
 } ;
  print_r($newCarrierAry($carrierAddedToList));

A: Since there's no in_array() that searches multi-dimensional elements, build an associative array that's keyed by the serviceMethod. Then you can use isset() to check whether we already have an element with that method.
$newArray = array();
foreach ($carrierAddedToList as $cK) {
    $sm = $cK['serviceMethod'];
    if (!isset($newArray[$sm]) || $newArray[$sm]['APIPriceTax'] > $cK['ApiPriceTax']) {
        $newArray[$sm] = $cK;
    }
}
// Now convert associative array to indexed:
$newArray = array_values($newArray);


text:
Q: Error al descargar un archivo de mi servidor con codeigniter Estoy trabajando en un proyecto en codeigniter 3, el problema que tengo es al momento de descargar el archivo, al momento de subir el archivo al servidor, guardo en la base de datos la ruta y el nombre generados por la función do_upload de codeigniter, cuando lo descargo lo descarga bien pero sin contenido, sea para documentos de word excel como pdf, al tratar de abrir estos archivos me los muestra vació y en el caso del pdf no lo abre, al ver los documentos en el servidor están todos completos con su contenido.
Al momento de enviar el archivo lo envio mediante ajax utilizando el FormData y lo envia de forma correcta.
Aqui el codigo de subir:
public function document(){
    $config['allowed_types']    = 'docx|xlsx|pdf';
    $config['upload_path']      = './assets/archivos/doc/';
    $config['remove_spaces']    = TRUE;
    $config['max_size']         = '20048';
    $this->load->library('upload', $config);
    if(!$this->upload->do_upload('file')){
        $error = $this->upload->display_errors();
        $result = array('error' => true, 'mens' => $error, 'estado' => 3);
        echo json_encode($result);
    }else{
        $data = array(
            'nom_doc'  => $this->upload->data('file_name'),
            'doc_size' => $this->upload->data('file_size'),
            'type_doc' => $this->upload->data('file_type'),
            'ruta_doc' => $this->upload->data('full_path'),
            'id_conf_sist' => 1
        );
        $res = $this->Config_model->insertDocument($data);
        if($res){
            $result = array('error' => false, 'mens' => 'El archivo '.$this->upload->data('raw_name').', a sido guardado correctamente.', 'estado' => 1);
            echo json_encode($result);
        }
    }
}

Este seria el código de descargar:
public function getDownloadFile($name){
    $data = file_get_contents($this->folder.$name);
    force_download($name,$data);
}

Alguien me podría decir cual seria el error por el cual no me descarga bien los archivos.

A: El error que ocurre es que estas utilizando mal el método force_download, ya que en la documentación oficial dice que para descargar un archivo existente en el servidor debes de utilizar el método de la siguiente manera:
public function getDownloadFile($name){
    //El primer parámetro es la locación del archivo y el segundo un NULL.
    force_download($this->folder.$name, NULL);
}

Te dejo la documentación oficial para mayor información:

https://www.codeigniter.com/userguide3/helpers/download_helper.html


text:
Q: ToDictionary error "Cannot apply indexing with [] to an expression of type 'method group'" I have the following code inside my asp.net mvc web application :-
 public void syncWithEX()
 {
     var EXresource = entities.Resources.Select(g => new
     {
         EXID = g.RESOURCEID,
         CurrentEXSiteID = g.ResourceLocation.SITEID
     }).ToDictionary(a => a.EXID, a => a.CurrentEXSiteID);
     var technology = ITSys.Technologies.Select(g => new
     {
          ID = g.TechnologyID,
          EXID = g.EXID
     }).ToDictionary(a => a.ID, a => a.EXID);

     var server = ITSys.ITSYSServers.Where(a => !a.Technology.IsDeleted && a.Technology.IsCompleted);
     foreach (var s in server)
     {
          long? EXid = technology[s.ITSYSServerID];
          if (EXresource.ContainsKey[EXid.Value] )
          {
              long? CurrentEXsiteid = EXresource[EXid.Value];
              if (CurrentEXsiteid != s.EXSiteID)
              {
                   s.EXSiteID = CurrentEXsiteid.Value;
                   ITSys.Entry(s).State = EntityState.Modified;
              }
          }
     }

But i am getting the following error :

Cannot apply indexing with [] to an expression of type 'method group

on the following code:
if (EXresource.ContainsKey[EXid.Value] )

A: change to:
if (EXresource.ContainsKey(EXid.Value))
Dictionary.ContainsKey()


text:
Q: Do String methods in Java run in O(1) time? This is my code to find the length of the longest substring without repeating characters. Does this code run in O(n) time? Or does it run in O(n^2) time? I am not sure if the String methods run in O(n) time or O(1) time.
A test case includes: "pwwkewo" returning 4 because "kewo" is the the longest substring inside the string that has unique characters.
public int lengthOfLongestSubstring(String s) {

    int maxLength = 0;
    String sub = "";

    for(int i=0; i<s.length(); i++) {

         //add that char to the sub string
         sub = sub + s.charAt(i);

        //if we find a char in our string
        if(sub.indexOf(s.charAt(i)) != -1) {

           //drop any replicated indexes before it
            sub = sub.substring(sub.indexOf(s.charAt(i)) + 1);
        }

        if(sub.length() > maxLength) {
            maxLength = sub.length();
        }

    }

    return maxLength;

}

A: sub.indexOf() can take linear time, since it might have to check all the characters of sub. And the length of sub is O(n) in the worst case (assuming your input has no repeating characters).
Therefore your total running time is O(n2), since the loop has n iterations and in each iteration you call indexOf().

A: Your code runs in O(n^2) as there is a for loop and inside it you call an indexOf() method. This in turn is O(n).
Thus your method is O(n^2).


text:
Q: addAttachment error in XML-RPC while using Java My Java code
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Vector;
import helma.xmlrpc.*;

public class test {

    private final static String server_url =
        "http://confluence.xyz.com:8080/rpc/xmlrpc";

    public static void main (String [] args) {
        try {

            XmlRpcClient server = new XmlRpcClient(server_url);

            Vector<Object> params = new Vector<Object>(2);
            params.add("user");
            params.add("pass");

            String token = (String) server.execute("confluence2.login", params );
            System.out.println(token);

            Vector<Object> page = new Vector<Object>(3);
            page.add(token);
            page.add("~username");
            page.add("test_page");

            Object token1 = server.execute("confluence2.getPage", page );
            System.out.println(token1.hashCode());

            String fileName  = "C:/New folder/a.jpeg";
            String contentType = "image/jpeg";

            Vector<Object> attachment = new Vector<Object>(2);
            attachment.add("a.jpeg");
            attachment.add(contentType);
            System.out.println(attachment);

            byte[] bytes = Files.readAllBytes(Paths.get(fileName));
            System.out.println(bytes);

            Vector<Object> attach = new Vector<Object>(4);
            attach.add(token);
            attach.add(token1.hashCode());
            attach.add(attachment);
            attach.add(bytes);
            System.out.println(attach);
            server.execute("confluence2.addAttachment", attach);

        }
         catch (Exception exception) {
            System.err.println("JavaClient: " + exception.toString());
        }
    }
}

Everything works fine except on line where "addAttachment" is called,
error i get is
JavaClient: helma.xmlrpc.XmlRpcException: java.lang.NoSuchMethodException: com.sun.proxy.$Proxy2104.addAttachment(java.lang.String, int, java.util.Vector, [B)

can anyone help me with any other library which i should be using. it seems helma.xmlrpc doesn't have addAttachment method

A: I used org.apache.xmlrpc.client.XmlRpcClient and not helma but the concepts should be the same.  It's not that "helma.xmlrpc doesn't have addAttachment method", it's just that you're calling addAttachment() with the wrong parameters. Try calling it with the proper parameters listed at https://developer.atlassian.com/confdev/confluence-rest-api/confluence-xml-rpc-and-soap-apis/remote-confluence-methods

addAttachment(String token, long contentId, Attachment attachment, byte[] attachmentData)

so for apache xmlrpc, my partial code looks like:
    //add attachment to the page
    byte[] bytes = FileUtils.readFileToByteArray(new File(FILE_TO_ATTACH));
    Map<String, String> attachInfo = new HashMap<String, String>();
    attachInfo.put("fileName", FILENAME);
    attachInfo.put("contentType", CONTENT_TYPE);
    attachInfo.put("comment", COMMENT);

    //actually add it now
    client.execute("confluence1.addAttachment", new Object[]{token, PAGEID, attachInfo, bytes});


text:
Q: microcontroller low battery indicator I am powering a board and circuit with a 9V battery (those alkaline ones). And I would like to read the 9V battery to keep track of how much power it has left. I have read that I can do this with a voltage divider since most ADC input on uCs take 5V max. That's good but wouldn't the voltage divider itself draw power and make the battery drain faster? I am not going to constantly measure battery level.

A: A high value resistor divider, as tcrosley suggests, is a good idea as a start, though there are a few "but"s.
The ADC's input impedance is usually quite low, so will have a big influence on a 1M\$\Omega\$ resistance. Also switching the I/Os to input will stop the current, but consequently the 9V will be on the inputs and you don't want that.
A solution could be to use a P-MOSFET to switch the resistor divider on and off. Choose a low-leakage FET like the FDG332PZ (just one of many type with a leakage current < 1\$\mu\$A). Remembering the low input impedance of the ADC we can then safely use a lower resistance divider. This will cause a larger current when switched on, but we only need it for a few \$\mu\$s every hour or day or so, so overall that's really negligible.

A: If you use a voltage divider with fairly high value resistors, e.g. two 499K in series and tap off the middle, your maximum voltage will be 4.5v and it will draw only 9 µA.
If even that much current were a concern, you could tie the bottom of the resistor divider into a open-drain output pin on the microcontroller and set it to ground only when you need to take a measurement.  In that case, you could get by with lower value resistors.
EDIT:
As Russel McMahon mentions, many micros won't allow the input of the ADC rise much above their supply voltage (VDD), which would happen when the ground was removed on the resistor divider.  So you would then need a high-side switch instead.


text:
Q: Dynamic dependant data validation in multiple cells I am banging my head with the following issue - I have a table where I input all invoices received with customer name, invoice number and amount. In a separate sheet I have a table where I enter all payments on invoices received.
In the Payments table I have created a data validation list for the Customer input column and I want to have another data validation for the invoice number based on the selected customer.
In other words I want to limit the invoice column to only include invoices from the selected customer.
I have attached a screenshot to demonstrate what I am trying to do.
Thank you for your support.


text:
Q: not getting query results from firebase realtime database with angularfire2 angular5 I am trying to query the firebase realtime database with Angular 5 ()
I have tried the new API but I am getting nowhere with Querying the real time database, the query runs but I get no results.
My data set is simple
Data structure
I can list all of the data without issue, but when I try and query results filtering on a field I get the two console log events, but empty data?? Any ideas??
I am using the following versions
    "@angular/cli": "1.6.3",
    "@angular/compiler-cli": "^5.0.0",
    "@angular/language-service": "^5.0.0",
    "angularfire2": "^5.0.0-rc.4",
    "firebase": "4.8.0",
   find(abn: string) {
      this.db.list<company>('/company', ref => ref.orderByChild('abn').equalTo(abn)).snapshotChanges().map(actions => {
         console.log(`Action: ${actions}`);
         return actions.map(action => ({ key: action.key, value: action.payload.val()}));
      }).subscribe(items => {
        this.query = items.map(item => ({key: item.key, value: item.value}));
        console.log(`Query Results: ${this.query}`);
      });
    }

A: So I figured out the mistake, the real time database actually types data. The abn field is a number and I was passing a string to the query. Changing it to a number works.


text:
Q: How can I fill a Matrix row by row So I have this problem:

A person has N shops in a city. Write a console app which receives from input:

*

*on the first line, N

*next N lines, each of them containing the profit of every shops for each of the year trimesters, with 2 decimals precision. Numbers are separated by one space.

Output :

*

*most profitable trimester;

*most profitable shop;

Example:
2
1000.50 2000.00 1000.00 3000.00
500.00 600.00 700.00 800.00

Result:
Trimester 4 : 3800.00 Shop 1 : 7000.50

Now about my question... I've written some code, but I don't know how to fill the matrix row by row. Here is my code:
class Program
{
    static void Main(string[] args)
    {
        const int numberOfTrimesters = 4;
        int numberOfShops = Convert.ToInt32(Console.ReadLine());
        double[,] shopsList = new double[numberOfShops, numberOfTrimesters];
        for (int i = 0; i < numberOfShops; i++)
        {
            string input = Console.ReadLine();
            string[] array = input.Split(' ');
            double[] shop = new double[array.Length];
            for (int j = 0; j < array.Length; j++)
                shop[j] = Convert.ToDouble(array[j]);
            for (int k = 0; k < numberOfShops; k++)
                for (int m = 0; m < numberOfTrimesters; m++)
                    shopsList[k, m] = shop[array.Length];
        }

The problem is on last line of the last for.


text:
Q: Loading Effect using JS and PHP I am working on a project in PHP and AIML where the bot replies to the user queries asked by a user through a microphone. I am new to jQuery and JS so I need help in implementing loading effect in between the user input and final output.
<?php
  $display = "";
  $thisFile = __FILE__;
  if (!file_exists('../../config/global_config.php'));
  require_once ('../../config/global_config.php');
  require_once ('../chatbot/conversation_start.php');
  $get_vars = (!empty($_GET)) ? filter_input_array(INPUT_GET) : array();
  $post_vars = (!empty($_POST)) ? filter_input_array(INPUT_POST) : array();
  $form_vars = array_merge($post_vars, $get_vars); // POST overrides and overwrites GET
  $bot_id = (!empty($form_vars['bot_id'])) ? $form_vars['bot_id'] : 1;
  $say = (!empty($form_vars['say'])) ? $form_vars['say'] : '';
  $convo_id = session_id();
  $format = (!empty($form_vars['format'])) ? $form_vars['format'] : 'html';
?>
<!DOCTYPE html>

    <title>Interact With Sia</title>

Talk to Sia

    <form id="chatform1" name="chatform" method="post" action="index.php#end" >

        <input type="text" name="say" id="say" size="70" onmouseover="startDictation()" style="color:red" />
        <input type="submit" class="say" name="submit" id="btn_say" value="say" />

        <input type="hidden" name="convo_id" id="convo_id" value="<?php echo $convo_id;?>" />
        <input type="hidden" name="bot_id" id="bot_id" value="<?php echo $bot_id;?>" />
        <input type="hidden" name="format" id="format" value="<?php echo $format;?>" />
    </form>

      <?php echo $display; ?> //THIS DISPLAYS THE OUTPUT TO THE QUERY

As soon as the page loads, the microphone in the user's browser is activated [via talk.js_startDictation()] and after the user finishes the voice input, the query is sent to the scripts and then the result is diplayed by <?php echo $display; ?>.
How can I implement a loading effect in place of <?php echo $display; ?> until the script returns the result of the query and updates the $display variable on the page?

A: You could use AJAX to archieve this, like:
1 - Load jquery.js (you could use CDN or download it).
2 - Create a div with a loader (usually a gif is fine, there are a lot). Hidde it with css: display:hidden;
3 - Add at the bottom of your page:

When the form is sumitted, jquery 'catch' the request, process the .submit() functions and send the data via post to a .php file (you should create it) and receive the params with $_POST. Something like:
yourPhpFile.php

<?php

    $convo_id = $data['convo_id'];
    //do something
    ...
?>


text:
Q: How to return empty abstract class data set (PostgreSQLResult)? I am trying to rewrite my code to make is null safety.
  PostgreSQLResult getResultFromCache(sqlQuery) {
    for (var req in requestsCacheList) {
      if(req.requestHash == sqlQuery.hashCode) {
        return req.requestResult;
      }
    }
    // var p = PostgreSQLResult(); // what should be here? Implementing PostgreSQLResult?
    // return p;
  }

I should to return here PostgreSQLResult instead of null. I looked sources what PostgreSQLResult is:
/// A single row of a query result.
///
/// Column values can be accessed through the `[]` operator.
abstract class PostgreSQLResultRow implements List {
  List<ColumnDescription> get columnDescriptions;

  /// Returns a two-level map that on the first level contains the resolved
  /// table name, and on the second level the column name (or its alias).
  Map<String, Map<String, dynamic>> toTableColumnMap();

  /// Returns a single-level map that maps the column name (or its alias) to the
  /// value returned on that position.
  Map<String, dynamic> toColumnMap();
}

/// The query result.
///
/// Rows can be accessed through the `[]` operator.
abstract class PostgreSQLResult implements List<PostgreSQLResultRow> {
  /// How many rows did this query affect?
  int get affectedRowCount;
  List<ColumnDescription> get columnDescriptions;
}

Could you show me how should be look empty result PostgreSQLResult set?


text:
Q: Warnings after moving Wordpress installation Since I reinstalled a website on a different hosting and moved the database and everything, I keep getting a lot of error messages when trying to open the website (www.pandasnacozinha.com.br). Some of the errors are:
Warning: file_exists() [function.file-exists]: open_basedir restriction in effect. File(/home/u332015957/public_html/wp-content/uploads/2015/05) is not within the allowed path(s): (/home/pandasnacozinha.com.br) in /home/pandasnacozinha.com.br/www/wp-includes/functions.php on line 1496

Warning: is_dir() [function.is-dir]: open_basedir restriction in effect. File(/home/u332015957/public_html/wp-content/uploads/2015) is not within the allowed path(s): (/home/pandasnacozinha.com.br) in /home/pandasnacozinha.com.br/www/wp-includes/functions.php on line 1501

Warning: is_dir() [function.is-dir]: open_basedir restriction in effect. File(/home/u332015957/public_html/wp-content/uploads) is not within the allowed path(s): (/home/pandasnacozinha.com.br) in /home/pandasnacozinha.com.br/www/wp-includes/functions.php on line 1501

I noticed something: my root directory in the old hosting was "public_html". The new hosting calls the root directory "www". I believe this is what might be causing the problem, but I don't know how to solve it.
Any thoughts would be appreciated.
Thank you,
Giovanna