text:
Q: How do I get the parent directory's name only, not full path? I am trying to get the parent directory's name only. Meaning, only its last component, not the full path.
So for example for the path a/b/c/d/e I want to get d, and not a/b/c/d.
My current code:
import os

path = "C:/example/folder/file1.jpg"
directoryName = os.path.dirname(os.path.normpath(path))
print(directoryName)

This prints out C:/example/folder and I want to get just folder.

A: Use pathlib.Path to get the .name of the .parent:
from pathlib import Path

p = Path("C:/example/folder/file1.jpg")
print(p.parent.name)  # folder

Compared to os.path, pathlib represents paths as a separate type instead of strings. It generally is shorter and more convenient to use.

A: The simplest way to do this would be using pathlib. Using parent will get you the parent's full path, and name will give you just the last component:
>>> from pathlib import Path
>>> path = Path("/a/b/c/d/e")
>>> path.parent.name
'd'

For comparison, to do the same with os.path, you will need to get the basename of the dirname of your path. So that translates directly to:
import os

path = "C:/example/folder/file1.jpg"
print(os.path.basename(os.path.dirname(path)))

Which is the nicer version of:
os.path.split(os.path.split(path)[0])[1]

Where both give:
'folder'

As you can see, the pathlib approach is much clearer and readable. Because pathlib incorporates the OOP approach for representing paths, instead of strings, we get a clear chain of attributes/method calls.
path.parent.name

Is read in order as:

start from path -> take its parent -> take its name

Whereas in the os functions-accepting-strings approach you actually need to read from inside-out!
os.path.basename(os.path.dirname(path))

Is read in order as:

The name of the parent of the path

Which I'm sure you'll agree is much harder to read and understand (and this is just a simple-case example).

You could also use the str.split method together with os.sep:
>>> path = "C:\\example\\folder\\file1.jpg"
>>> path.split(os.sep)[-2]
'folder'

But as the docs state:

Note that knowing this [(the separator)] is not sufficient to be able to parse or
  concatenate pathnames — use os.path.split() and os.path.join() — but
  it is occasionally useful.

A: this works
path = "C:/example/folder/file1.jpg"
directoryName = os.path.dirname(path)
parent = directoryName.split("/")
parent.reverse()
print(parent[0])

A: Simple to solve using pathlib
0. Import Path from pathlib
from pathlib import Path
path = "C:/example/folder/file1.jpg"

1. Get parent level 1
parent_lv1 = Path(path).parent

2. Get parent level 2
parent_lv2 = parent_lv1.parent

3. Get immediate parent
imm_parent = parent_lv1.relative_to(parent_lv2)
print(imm_parent)

A: I prefer regex
import re

def get_parent(path: str) -> str:
    match = re.search(r".*[\\|/](\w+)[\\|/].*", path)
    if match:
        return match.group(1)
    else:
        return ""

if __name__ == '__main__':
    my_path = "/home/tony/some/cool/path"
    print(get_parent(my_path))
    win_path = r"C:\windows\path\has\dumb\backslashes"
    print(get_parent(win_path))

Output
cool
dumb


text:
Q: antd module.exports = exports['default']; is not working As antd described I am using babel-plugin-import and I have added following babel loader in webpack config.
webpack.config
{
  test: /\.js?$/,
  loader: 'babel-loader',
  exclude: /node_modules/,
  query: {
   presets: ['react', 'es2015'],
   "plugins": [
     ["import", { libraryName: "antd", style: "css" }]
    ]
  }
}

MyApp.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Modal, Button, Checkbox, Table, Icon, Badge, Alert, notification, Row, Col } from 'antd';
const { Column, ColumnGroup } = Table;

class MyApp extends Component {
   constructor(props) {
    super(props);
   }

   render() {
    let template = <Table dataSource={dataSource} columns={columns} />
    return (template);
   }
}
export default MyApp;

The error is
Uncaught Error: Element type is invalid: expected a string (for built-in components)
or a class/function (for composite components) but got: object.
Check the render method of `Table`.
    at invariant (invariant.js:44)
    at instantiateReactComponent (instantiateReactComponent.js:74)
    at instantiateChild (ReactChildReconciler.js:44)
    at ReactChildReconciler.js:71
    at traverseAllChildrenImpl (traverseAllChildren.js:77)
    at traverseAllChildrenImpl (traverseAllChildren.js:93)
    at traverseAllChildren (traverseAllChildren.js:172)
    at Object.instantiateChildren (ReactChildReconciler.js:70)
    at ReactDOMComponent._reconcilerInstantiateChildren (ReactMultiChild.js:187)
    at ReactDOMComponent.mountChildren (ReactMultiChild.js:226)

package.json
{
  "name": "myapp",
  "version": "1.0",
  "repository": "",
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --colors",
    "dev": "cross-env NODE_ENV=development webpack-dev-server --progress --inline --historyApiFallback",
    "start": "npm run dev",
  },
  "dependencies": {
    "animate.css": "^3.5.2",
    "antd": "^2.10.2",
    "axios": "^0.15.3",
    "babel-core": "^6.14.0",
    "babel-plugin-add-module-exports": "^0.2.1",
    "babel-plugin-angularjs-annotate": "^0.5.2",
    "babel-plugin-syntax-flow": "^6.13.0",
    "babel-plugin-transform-runtime": "^6.12.0",
    "babel-preset-es2015": "^6.16.0",
    "babel-preset-es2017": "^6.16.0",
    "babel-preset-react": "^6.23.0",
    "babel-preset-stage-1": "^6.16.0",
    "babel-runtime": "^6.11.6",
    "cidr-regex": "^1.0.6",
    "create-react-class": "^15.5.3",
    "d3": "^3.5.16",
    "debug": "2.2.0",
    "es6-promise": "^4.0.3",
    "express": "4.9.8",
    "file-saver": "^1.3.3",
    "filesaver.js": "^0.2.0",
    "fixed-data-table": "0.6.0",
    "font-awesome": "^4.7.0",
    "formsy-react": "0.17.0",
    "html2canvas": "^0.5.0-beta4",
    "jquery": "^3.2.1",
    "lodash": "^4.17.4",
    "manifest-revision-webpack-plugin": "^0.3.0",
    "netmask": "^1.0.5",
    "node-waves": "^0.7.5",
    "normalize-css": "^2.3.1",
    "object-assign": "2.0.0",
    "prop-types": "~15.5.10",
    "react": "~15.5.4",
    "react-axios": "0.0.9",
    "react-custom-scrollbars": "^4.0.0",
    "react-dom": "~15.5.4",
    "react-google-maps": "4.7.2",
    "react-iframe": "0.0.4",
    "react-modal": "~0.6.1",
    "react-router": "^2.8.1",
    "react-router-dom": "^4.0.0",
    "react-tooltip": "^3.3.0",
    "reactable": "0.12.0",
    "rickshaw": "^1.6.0",
    "semver": "^5.3.0",
    "url": "^0.11.0",
    "webpack": "2.1.0-beta.25"
  },
  "devDependencies": {
    "assets-webpack-plugin": "^3.4.0",
    "autoprefixer": "^6.5.0",
    "babel-core": "^6.24.0",
    "babel-loader": "^6.4.1",
    "babel-plugin-import": "^1.1.1",
    "babel-preset-env": "^1.2.2",
    "baggage-loader": "^0.2.4",
    "clean-webpack-plugin": "^0.1.10",
    "copy-webpack-plugin": "^4.0.1",
    "cross-env": "^3.0.0",
    "css-loader": "^0.25.0",
    "eslint": ">=1.6.0 <4.0.0",
    "eslint-loader": "~1.5.0",
    "extract-text-webpack-plugin": "^2.0.0-beta.4",
    "file-loader": "^0.9.0",
    "html-loader": "^0.4.4",
    "html-webpack-plugin": "^2.22.0",
    "imagemin-pngquant": "^5.0.0",
    "jasmine": "^2.2.1",
    "jasmine-core": "^2.2.0",
    "json-loader": "^0.5.4",
    "karma": "^0.13.2",
    "karma-jasmine": "^0.3.5",
    "karma-phantomjs2-launcher": "^0.5.0",
    "karma-webpack": "^1.6.0",
    "node-sass": "^3.4.0",
    "node-static": "^0.7.9",
    "postcss-loader": "^0.13.0",
    "resolve-url-loader": "^2.0.2",
    "sass-loader": "^4.0.2",
    "style-loader": "^0.13.1",
    "url-loader": "^0.5.7",
    "webpack-dev-server": "2.1.0-beta.7"
  },
  "engines": {
    "node": ">=4.0.0"
  }
}

A: Without seeing your actual datasource and column variable declaration, It is tough to tell as from your error code, It seems you are not providing the arguments to Table in correct format.
Here is an example for datasource and column.
const dataSource = [{
  key: '1',
  name: 'Mike',
  age: 32,
  address: '10 Downing Street'
}, {
  key: '2',
  name: 'John',
  age: 42,
  address: '10 Downing Street'
}];

const columns = [{
  title: 'Name',
  dataIndex: 'name',
  key: 'name',
}, {
  title: 'Age',
  dataIndex: 'age',
  key: 'age',
}, {
  title: 'Address',
  dataIndex: 'address',
  key: 'address',
}];

Also, I don't know your folder structure, but if your files are in a different folder then you might wanna add something like this to your webpack config.
include: path.join(__dirname, 'your_folder_name_goes_here')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typescript overload/edit given types by 3rd library component in React.js typescript beginner here.
I am trying to convert my existing react project to use typescript.
Now I changed my file to tsx, and got bunch of errors most I could fix.
But I am stuck with 1 type I cannot find answers to online, To overload 3rd library types with my own.
For example, I am using ant design for my components which brings its own types inside:
import React from 'react';
import { Select, Form } from 'antd';
import { AdvancedSelectPROPS, selectOptionItem } from '../types';
const FormItem = Form.Item;
const Option = Select.Option;

const SelectElement = React.memo(function InputElement(props: AdvancedSelectPROPS) {
    const { status, hasfeed, error, label, formItemStyle, disabled, forwhom, value, options = [], ...otherProps } = props;

    return (
        <FormItem
            validateStatus={disabled ? (status === 'error' ? 'error' : 'warning') : status === 'error' ? 'error' : ''}
            className="addLabel"
            hasFeedback={hasfeed === 'true'}
            help={status === 'error' ? error : ''}
            style={formItemStyle}
            label={label}
        >
            <Select {...otherProps} disabled={disabled} value={!value ? [] : value} forwhom={forwhom}>
              // I have added new prop "forwhom" which is not provided by the types of ant design
                {options.map((item: selectOptionItem, index) => {
                    return (
                        <Option value={item.value} key={item.name + index}>
                            {item.name || item.Name}
                        </Option>
                    );
                })}
            </Select>
        </FormItem>
    );
});

export default SelectElement;

I have added new prop "forwhom" which is not provided by the types of ant design.
Now I would like to add new props and their types to the built in types, how is something like that is done?
I tried
declare namespace JSX {
  interface Select {
        forwhom: string | number
    }
}

or
declare namespace JSX {
    interface IntrinsicAttributes {
        forwhom: string | number
    }
    interface IntrinsicClassAttributes {
        forwhom: string | number
    }
}

But it didnt work.
Error:
Property 'forwhom' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Select<any>> & Pick<Pick<Readonly<SelectProps<any>> & Readonly<{ children?: ReactNode; }>, "disabled" | "style" | "prefixCls" | ... 50 more ... | "loading"> & Pick<...> & Pick<...>, "disabled" | ... 51 more ... | "loading"> & Partial<...> & Partial<...>

Thanks for your help.

A: Try this:
// types/antd.ts
declare module "antd/lib/select" {
  export interface SelectProps {
    forwhom: string | number;
  }
}

export {}; // you only need this line if "--isolatedModules" is provided to tsc

After that you need to import both, your custom typing (here ./types/antd.ts) and the Select from antd:
import "./types/antd";
import { Select } from "antd";

// ...

<Select forwhom={1} /> // works

Codesandbox


text:
Q: Error NU1605: Docker restore nuget packages failed I am running my .netcore3.1 microservices into docker, for this I have added docker(window based) file into service.
When I run microservice with docker its throw error on step 'determining projects to restore...'
error
warning NU1603: Team.Api depends on ExceptionHandler (>= 1.0.0-CI-20200424-092531) but ExceptionHandler 1.0.0-CI-20200424-092531 was not found. An approximate best match of ExceptionHandler 1.0.0 was resolved.
    1>/src/TeamApi/Team.Api.csproj : warning NU1603: Team.Api depends on MessageBroker (>= 1.0.0-CI-20200923-130139) but MessageBroker 1.0.0-CI-20200923-130139 was not found. An approximate best match of MessageBroker 1.0.0 was resolved.
    1>/src/TeamApi/Team.Api.csproj : error NU1101: Unable to find package MessageBrokerRabbitMQ. No packages exist with this id in source(s): nuget.org
    1>/src/TeamApi/Team.Api.csproj : warning NU1701: Package 'ExceptionHandler 1.0.0' was restored using '.NETFramework,Version=v4.6.1, .NETFramework,Version=v4.6.2, .NETFramework,Version=v4.7, .NETFramework,Version=v4.7.1, .NETFramework,Version=v4.7.2, .NETFramework,Version=v4.8' instead of the project target framework '.NETCoreApp,Version=v3.1'. This package may not be fully compatible with your project.
    1>/src/TeamApi/Team.Api.csproj : error NU1605:  Team.Api -> MessageBroker 1.0.0 -> Microsoft.Extensions.Hosting 3.1.3 -> Microsoft.Extensions.Logging.Debug (>= 3.1.3)
    1>/src/TeamApi/Team.Api.csproj : error NU1605: Detected package downgrade: Microsoft.Extensions.Logging.Debug from 3.1.3 to 3.1.1. Reference the package directly from the project to select a different version.
    1>/src/TeamApi/Team.Api.csproj : error NU1605:  Team.Api -> Microsoft.Extensions.Logging.Debug (>= 3.1.1)
    1>  Failed to restore /src/TeamApi/Team.Api.csproj (in 52.24 sec).

docker throw error on randomly package on every build
Docker specs which I am using are:
Windows version: 1903 (18362.418)
Docker Desktiop version: 3.1.0 (51484)
Engine: 20.10.2

Docker file created by Visual Studio 2019
FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
WORKDIR /src
COPY ["TeamApi/Team.Api.csproj", "TeamApi/"]
RUN dotnet restore "TeamApi/Team.Api.csproj"
COPY . .
WORKDIR "/src/TeamApi"
RUN dotnet build "Team.Api.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "Team.Api.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "Team.Api.dll"]

I have created docker file for Linux as well but the result is same
Update1: Project's .csproj file
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
    <UserSecretsId>1d75b031-5ef6-420a-9f88-5b2bb3b78187</UserSecretsId>
    <DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
  </PropertyGroup>

  <ItemGroup>
    <Compile Remove="Infrastructure\20200116074051_TeamDB.cs" />
    <Compile Remove="Infrastructure\20200116074051_TeamDB.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200116102750_CompanyID.cs" />
    <Compile Remove="Infrastructure\Migrations\20200116102750_CompanyID.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200116103510_CompanyIDcccc.cs" />
    <Compile Remove="Infrastructure\Migrations\20200116103510_CompanyIDcccc.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200116110757_UserTable.cs" />
    <Compile Remove="Infrastructure\Migrations\20200116110757_UserTable.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200116111728_UserTable.cs" />
    <Compile Remove="Infrastructure\Migrations\20200116111728_UserTable.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200120064812_new.cs" />
    <Compile Remove="Infrastructure\Migrations\20200120064812_new.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200120065302_UpdateUser.cs" />
    <Compile Remove="Infrastructure\Migrations\20200120065302_UpdateUser.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200120065757_UpdateUser.cs" />
    <Compile Remove="Infrastructure\Migrations\20200120065757_UpdateUser.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200120065948_UpdateUser.cs" />
    <Compile Remove="Infrastructure\Migrations\20200120065948_UpdateUser.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200122052759_CompanyUpdate.cs" />
    <Compile Remove="Infrastructure\Migrations\20200122052759_CompanyUpdate.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200122063655_UpdateCompanyAndUser.cs" />
    <Compile Remove="Infrastructure\Migrations\20200122063655_UpdateCompanyAndUser.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200122064700_UpdateCompany.cs" />
    <Compile Remove="Infrastructure\Migrations\20200122064700_UpdateCompany.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200122102506_Updated.cs" />
    <Compile Remove="Infrastructure\Migrations\20200122102506_Updated.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200123051214_TeamDB.cs" />
    <Compile Remove="Infrastructure\Migrations\20200123051214_TeamDB.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200123133951_CompanyRelation.cs" />
    <Compile Remove="Infrastructure\Migrations\20200123133951_CompanyRelation.Designer.cs" />
    <Compile Remove="Infrastructure\Migrations\20200123134744_CompanyRelationUpdate.cs" />
    <Compile Remove="Infrastructure\Migrations\20200123134744_CompanyRelationUpdate.Designer.cs" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Autofac.Extensions.DependencyInjection" Version="6.0.0" />
    <PackageReference Include="AutoMapper" Version="9.0.0" />
    <PackageReference Include="DocumentFormat.OpenXml" Version="2.10.0" />
    <PackageReference Include="ExceptionHandler" Version="1.0.0-CI-20200424-092531" />
    <PackageReference Include="Hangfire.AspNetCore" Version="1.7.11" />
    <PackageReference Include="HangFire.Core" Version="1.7.11" />
    <PackageReference Include="Hangfire.MemoryStorage" Version="1.7.0" />
    <PackageReference Include="HangFire.SqlServer" Version="1.7.11" />

    <PackageReference Include="MessageBroker" version="1.0.0-CI-20200923-130139"/>
    <PackageReference Include="MessageBrokerRabbitMQ" version="1.0.0-CI-20200923-130139"/>

    <PackageReference Include="linqtotwitter" Version="5.0.0" />

    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.6" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.RazorPages" Version="2.2.5" />
    <!--<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="2.9.8">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>-->
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="3.1.1" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.9.10" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="3.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="3.1.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
    <PackageReference Include="EntityFramework" Version="6.4.0" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="7.0.0" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.1">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
    </PackageReference>
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="RabbitMQ.Client" Version="5.1.2" />
    <PackageReference Include="Serilog" Version="2.9.0" />
    <PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="5.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="5.0.0" />
    <PackageReference Include="Swashbuckle.AspNetCore.SwaggerUI" Version="5.0.0" />
    <PackageReference Include="Polly" Version="7.2.0" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.7.1" />
    <PackageReference Include="Z.EntityFramework.Plus.EFCore" Version="3.0.39" />
  </ItemGroup>

  <!--<ItemGroup>
    <ProjectReference Include="..\MessageBrokerRabbitMQ\MessageBrokerRabbitMQ.csproj" />
    <ProjectReference Include="..\MessageBroker\MessageBroker.csproj" />
  </ItemGroup>-->

</Project>

Update2

A: The RINFeed NuGet Source is missing from your container NuGet config, this source exist in one of your NuGet config hierarchy
You have two choice:

*

*Create a nuget.config (or use the existing with RINFeed) and copy it to the container
COPY "nuget.config" .

*Run a command into the container to add the source
dotnet nuget add source ....
See this stackoverflow question as a guide.
Warning
The URL in the RINFeed must be resolved by DNS container


text:
Q: C# Program gets stuck in FtpWebResponse after server disconnects I have a C# program that checks a ftp directory for new files every x seconds. If a new file is found it is downloaded. That works fine. If I start the program without running the ftp server the program loops and returns a message that the server cannot be reached. Then I start the server and the program connects as it should. But if I quit the ftp server again my program gets stuck in the FtpWebResponse.
I have a using statement block in a try catch block to close all connections.
while (true)
{
    //...
    FtpFileList = null;
    while (FtpFileList == null)
    {
        FtpFileList = await GetFtpFileList(adress, user, password);
        await Task.Delay(3000);
    }
    await Task.Delay(27000);
    //...
}

public static async Task<List<string>> GetFtpFileList(string address, string user, string password)
{
    try
    {
        List<string> returnValue = new List<string>();
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        request.Credentials = new NetworkCredential(user, password);
        using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync()) //The program gets stuck here
        {
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            while (reader.Peek() >= 0)
            {
                returnValue.Add(reader.ReadLine());
            }
        }
        AddToLogFile(DateTime.Now + ": " + "FTP directory updated");
        return returnValue;
    }
    catch (WebException e)
    {
        AddToLogFile(DateTime.Now + ": " + e.Message);
        return null;
    }
}

I expect the program to reconnect to the server after the connection was lost but instead it gets stuck.
Any help and hints how to solve that issue is appreciated.

A: Just to let you know I solved the issue by implementing a workaround: Instead of using await request.GetResponseAsync() I use the normal GetResponse() method in another thread which works without any problems so far: await Task.Run(() => request.GetResponse())

A: Use FtpWebRequest.GetResponse instead of FtpWebRequest.GetResponseAsync ( as GetResponseAsync is not overridden in FtpWebRequest and comes from the base WebRequest class, where it seems to it can't handle some specific FTP use cases)
If you need to await something just replace this:
FtpWebRequest request = ...
var response = (FtpWebResponse) await request.GetResponseAsync();
return response;

with that:
var response = (FtpWebResponse) request.GetResponse();
return await Task.FromResult(response);


text:
Q: Slow Magento - Mage_Core_Model_Session For some reason this past week my magento store has started loading slowly, particularly the time to first byte being the issue.
I've disabled an extension that I installed but to no avail. I've ran the profiler and the slowest loading item is
CORE::create_object_of::Mage_Core_Model_Session
Has anyone seen this before? I'm having trouble finding anything online.
The site is memcached and session data is stored using the DB.
Before this last week the site was loading quickly, so not 100% sure what has caused such a change.
Any help would be appreciated, I'm not sure if I can single out the session object in the profiler?
The website in question is www.normadorothy.com
Thanks

A: You need to try move session storage from MySQL to Memcached or even better to Redis, since you already use Memcached for cache storage - check Cm_RedisSession for extension and local.xml config sample with Redis as session storage.


text:
Q: How to find all occurrences of an element in a list? I read the post:  How to find all occurrences of an element in a list?
How to find all occurrences of an element in a list?
The answer given was:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]

I know this is list comprehension but I cannot break this code down and understand it.  Can someone please piece meal it for me?

If do the following code:I know enumerate will just create a tuple:
l=['a','b','c','d']
enumerate(l)

output:
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')

If there's a simpler way I'd be open to that too.

A: indices = [i for i, x in enumerate(my_list) if x == "whatever"] is equivalent to:
# Create an empty list
indices = []
# Step through your target list, pulling out the tuples you mention above
for index, value in enumerate(my_list):
    # If the current value matches something, append the index to the list
    if value == 'whatever':
        indices.append(index)

The resulting list contains the index positions of each match. Taking that same for construct, you can actually go deeper and iterate through lists-of-lists, sending you into an Inception-esque spiral of madness:
In [1]: my_list = [['one', 'two'], ['three', 'four', 'two']]

In [2]: l = [item for inner_list in my_list for item in inner_list if item == 'two']

In [3]: l
Out[3]: ['two', 'two']

Which is equivalent to:
l = []
for inner_list in my_list:
  for item in inner_list:
    if item == 'two':
      l.append(item)

The list comprehension you include at the beginning is the most Pythonic way I can think of to accomplish what you want.

A: indices = []
for idx, elem in enumerate(my_list):
    if elem=='whatever':
        indices.append(idx)


text:
Q: Piggy-backing off power amplifier outputs My motor-scooter has a built in radio, with a small speak either side of the front panel, below the handlebars.  It's a JonWay, i.e. cheap Chinese, so I suspect the radio is more suited to developing countries where helmets are not yet mandatory.
For me to listen while wearing a helmet, I need zero traffic, or a headphone jack, and I'd like to do the jack myself.  I may not find the radio board without too much dismantling, but the speakers are very accessible, so I may have to grab my input signal directly from them.
My electronics knowledge has all but evaporated after 15 years of non-use, so all I can start with is that I'll need a high impedance input, to make the increased load on the amp negligible, and my own power amp stage.  Where do I go from here?  I would like to do a rough design myself, maybe make the amp component a kit, but nothing ready made.

A: Don't worry about the input impedance of the stage.  Even a low 1 kΩ impedance will only decrease the load from 8 Ω to 7.94 Ω.  A more typical 10 kΩ will be invisible to the power amplifier.
Power amp for driving headphones is pretty easy.  In fact, you could just do it all in one stage.  See the CMoy amp for a popular and simple design:

*

*http://tangentsoft.net/audio/cmoy-tutorial/

*http://gilmore2.chem.northwestern.edu/projects/cmoy2_prj.htm

If your headphone amp will be battery-powered and mono, just connect the input of this schematic to the red wire of the speaker, and the ground to the black wire.
If you want to run stereo, or power it from the same supply so you don't need batteries, then you need to check whether the speakers are driven bridged or not.  With a signal coming through them, you should always see an AC voltage between the two terminals of a speaker (to make sure you're measuring right).  Then check if there's also a voltage between each terminal and ground.  If there is, then it's bridged.  If one wire has zero volts to ground, then it's ground.  You can make sure with a resistance check.
If it's not bridged, then you can just do the same thing with two amps.
If it is bridged, you can't use that circuit.  You don't want to short the active speaker outputs to ground or short the left and right outputs to each other. So you'd need to build a diff amp for each input stage, and connect ground to ground, V1 to one speaker wire (red), and V2 to the other (black):

Then Vout of this circuit connects to Vin of the previous headphone amplifier circuit.
If the speakers are driven class D, you might need additional filtering, but probably not.

A: You can grab the input signal off of the speaker or replace the speaker
with a power resistor. The radio is designed to drive a low-impedance
so you want to keep a low impedance on the output and amplify from there.
I did this with a car radio/cassette deck so that I could listen
to some old cassettes on my home stereo.
For the amplifier you could use an amplifier IC like the TDA7056A from Phillips (and IIRC
others). There may be single package audio amp ICs from National
and TI that could. The TDA7056A is a large through-hole package
with a metal-tab for heatsinking.
You may be better-off using a small portable radio or ipod like gadget
and coming off of the headphone jack.

A: What you actually want is to reduce or attenuate the voltage down to headphone levels. A voltage divider(or L-Pad as audiophiles call them) will do that just fine, and only needs two resistors. The only downside is that the resistors might get a little warm so use ones that are rated for 10 watts or so.
I'd say a use a ten ohm and a one ohm and put the headphone out across the one ohm.
Lots of people are making "L pad headphone attenuators", I'm sure the audio nerds know more than I do about them.
I've also heard of transformers being used.


text:
Q: Chrome Driver not working on android real devices using Appium I have installed the chrome driver - version 37.0 and source -com.android.chrome-1.apk
Started the adb command and device is connecting properly. Enable the debug mode and checked usb device option

Capabilties -

below is code snippet which i have used to call the chrome browser
     capabilities.setCapability("appium-version", "1.0");
            capabilities.setCapability("platformName", "Android");
            capabilities.setCapability("platformVersion", "4.3");
            capabilities.setCapability("deviceName", "abc");
            capabilities.setCapability("browserNamex", "Chrome");
        driver = new RemoteWebDriver(new URL("http://0.0.0.0:4723/wd/hub"),capabilities);

Getting below error -

error: Chromedriver create session did not work. Status was 200 and body was {"sessionId":"e70c1dff331b9b35ce5e4b974ae3d47e","status":13,"value":{"message":"unknown error: com.android.browser is not installed on device 43001beab8cb1161\n (Driver info: chromedriver=2.10.267517,platform=Mac OS X 10.9.2 x86_64)"}}
debug: Cleaning up appium session
error: Failed to start an Appium session, err was: Error: Did not get session redirect from Chromedriver
info: <-- POST /wd/hub/session 500

A: i am using appium on windows for android. try using appium 1.1.0.0 just launch server through appium. set these capabilities in Eclipse
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(MobileCapabilityType.BROWSER_NAME,"Chrome");
    capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,"4.3");
    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME,"Android");
    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME,"GT-I9300");
    driver = new RemoteWebDriver(new URL(:1:4723/wd/hub"), capabilities);

its working for me .
thanks
Rohit Vyas

A: I had the same issue and found that I was running version of chrome browser which is less than 33 and this requires devices to be rooted. I update chrome browser to 40+ (I guess it was 48) and issue disappeared.
Device rooting requirement for version of chrome lower than 33 is available here -
http://appium.io/slate/en/master/?ruby#mobile-chrome-on-emulator-or-real-device

A: Maybe it will help someone looking for solution to this error:

error: Chromedriver create session did not work. Status was 200 and
  body was
  {"sessionId":"e70c1dff331b9b35ce5e4b974ae3d47e","status":13,"value":{"message":"unknown
  error: com.android.browser is not installed on device
  43001beab8cb1161\n (Driver info: chromedriver=2.10.267517,platform=Mac
  OS X 10.9.2 x86_64)"}} debug: Cleaning up appium session error: Failed
  to start an Appium session, err was: Error: Did not get session
  redirect from Chromedriver

After long struggle with that, what helped me was overwriting the original chromedriver (the one that gets automatically downloaded when you run ./reset.sh --android ) in [my appium installation location]/build/chromedriver/linux with a file manually downloaded from this site.
Make sure you delete old chromedriver and name the new one the same as the deleted one.
I am using chromedriver 2.12

A: Based on this "unknown error: com.android.browser is not installed on device", it appears to be looking for the default browser instead of Chrome.
I notice there is a capability misspelled.  It should be "browserName" instead of "browserNamex" like you have.  That may be why it's not looking for the correct app package.

A: Replace chromedriver 2.18.343845 to 2.20.353145, you problem will sove in C:\Program Files (x86)\Appium\node_modules\appium\node_modules\appium-chromedriver\chromedriver\win path


text:
Q: Android (5.0.1) Chrome is deleting javascript whitespace and comments, is there a way to stop this? In addition to making debugging almost impossible, this new behavior is breaking my website where I use the heredoc javascript technique, (Javascript heredoc) which depends on using comments.
I'm not sure if I inadvertably turned this on, and this is a rare occurrence, or if this is a new Android feature.  I'm concerned because I use the heredoc javascript technique on a number of different sites, and this behavior will break these sites.
Has anyone else experienced this?
Is there a workaround where the server can stop this?
Is there an alternative to the heredoc javascript technique?

A: This problem was caused by  chrome data-compression (https://developer.chrome.com/multidevice/data-compression.)  Thank to Slaks for the heads up, or I would have missed it.
Once I turned it off - it's in Chrome Settings - Reduce data usage (after Content Settings and before About Chrome), my site began to work again.
In order to fix it for other users who like me are not even aware that they are using this,
I added the following code, that I found in the two references below:

<FilesMatch "\.(css|js)$">
    <IfModule mod_headers.c>
        Header set Pragma "public"
        Header set Cache-Control "no-transform,public, must-revalidate, proxy-revalidate"
    </IfModule>
    FileETag MTime Size
</FilesMatch>

The important part is telling Google "no-transform" on the javascript via the Cache-Control directive.  I did this for both .js and .css files, though I might add additional types in the future.
And, I added headers.load to mods-available to that it would have mod_headers.
http://mobiforge.com/design-development/setting-http-headers-advise-transcoding-proxies
Apache -Caching: How to Configure Response headers in Apache 2+.
After restarting Apache, everything worked fine.
In terms of the 3rd question, is there a workaround for the javascript heredoc method, I don't really have an answer, but perhaps this scenario is indicative that this method is not without problems.

A: I'm the tech lead for the Google compression proxy. Our proxy does indeed remove comments from JS files, which should be safe - although there are some tools which (perversely, in my opinion :-) rely on JS comments to work. In general there is no good way to detect this, so we rely on the Cache-Control: no-transform header. If you have suggestions for better ways to avoid this I'd appreciate it.


text:
Q: PHP Encontrar diretório informando parte do nome do diretório Olá!
Já possuo um protótipo de aplicação funcionando em PHP, onde acesso fotos de determinado diretório. Porém, os diretórios não ficaram muito amigáveis, por exemplo:
2016/783/01/2016-07-26-00001

Para ficar um pouco mais amigável, seria interessante que o terceiro e quarto elementos que são respectivamente categoria e evento, pudessem ter um nome à direita.
Ficando assim:
2016/783/01-relatorios/2016-07-26-00001-relatorio semanal 21

O que eu gostaria era acessar essa mesma pasta porém ignorando totalmente os textos do caminho, onde basicamente o código ignoraria os textos.
Nunca precisei fazer isso, estou lendo tudo a respeito do Filesystem e correlatos, mas ainda não achei uma solução!
Estas pastas estão todas linkadas com banco de dados, em tese não há necessidade alguma de fazer essa inclusão dos textos no caminho, porém, estou pensando em implementar isso, porque num futuro creio que alguém que for mexer no Backup vai acabar me causando problemas porque não está entendendo nada.
Obrigadão!

A: Isso deve servir para o que você quer:
<?php
$dir = "2016/783/01-relatorios/2016-07-26-00001-relatorio semanal 21";

$peaces = explode("/", $dir);

foreach ($peaces as $idx => $peace) {
    if (preg_match("/-\D+/", $peace, $match)) {
        $new_peace = substr($peace, 0, strpos($peace, $match[0]));
        $peaces[$idx] = $new_peace;
    }
}

$dir = implode("/", $peaces);
echo $dir;
?>

Estamos buscando um padrão pelo caractere (-) seguido de não dígitos.
A saída será:
2016/783/01/2016-07-26-00001


text:
Q: Hibernate Search @IndexedEmbedded on a polymorphic relationship (@Any, @ManyToAny) I'm using Hibernate Search and looking to index an object that has polymorphic relationships that use @Any and/or @ManyToAny.
@Indexed
public class Foo {
    @Any(metaDef="fooOwnerType", metaColumn=@Column(name="ownerType"))
    @JoinColumn(name="ownerId")
    @IndexedEmbedded // this DOES NOT WORK
    private OwnerType owner;

    @OneToOne
    @IndexedEmbedded // this WORKS
    private User user;

    @OneToOne
    @IndexedEmbedded // this WORKS
    private Company company;

    @Field
    private String description;
}

@Indexed
public class User implements OwnerType {
    @Field
    private String name;

    @Field
    private String address;
}

public class Company implements OwnerType {
    @Field
    private String name;
}

public interface OwnerType {
}

I can search and find Foo objects using text in the description field without issue. What I'd also like to do is find Foo objects when User.name or User.address is matched... but Hibernate Search doesn't seem to index these fields for me due to the polymorphic relationship OwnerType owner.
It would work fine if I use @IndexedEmbedded on a concrete object (User or Company) directly as expected.

A: Yes, this is expected. @IndexedEmbedded only adds fields for the exposed type of the embedded field. There are no concrete plans to fix it at the moment, but there is a feature request here: https://hibernate.atlassian.net/browse/HSEARCH-438
Also, interfaces cannot be mapped for indexing, only classes can. This will be fixed in Search 6: https://hibernate.atlassian.net/browse/HSEARCH-1656
One way to make your code work would be to turn OwnerType into an abstract class, either a @MappedSuperclass or an @Entity, and move the fields that are common to every subclass there.
EDIT: If the user/company associations are mutually exclusive (only one can be non-null), another way to make it work would be to simply query both. For example instead of querying owner.name, query both fields user.name and company.name. The Hibernate Search DSL allows that: just use .onFields("user.name", "company.name") instead of .onField("owner.name").


text:
Q: Issue with conditionals inside of a for loop (JAVA) Im learning programming with my group of friends and we are seriously stucked with something that looks pretty easy at first sight.
Basically we have a for loop that runs once. Inside we get some user input. Then we use a conditional to establish if we should add +1 to countM (Male count) or +1 to countF (Female count) instead.
PROBLEM -> The issue comes on the conditionals. When the user input is "F", the programm should be executing countF++, (if the requirements are fullfiled) however countM++ is the one executing everysingle time even if the user input is F and not M.
public static void main(String[] args) {

    int countM = 0;
    int countF = 0;

    int peso;
    int estatura;
    String sexo;

    for (int i = 1; i <= 2; i++) {

        if(i == 2){
          JOptionPane.showMessageDialog(null, "El nº de chicos aptos es " + countM);
          JOptionPane.showMessageDialog(null, "El nº de chicas aptas es " + countF);
          break;
        }

        JOptionPane.showMessageDialog(null, "Teclea los datos del alumno nº "+ i);

        estatura = Integer.parseInt(JOptionPane.showInputDialog("Teclea la estatura del alumno (cm)"));
        peso = Integer.parseInt(JOptionPane.showInputDialog("Teclea el peso del alumno en kg"));
        sexo = JOptionPane.showInputDialog("Teclea el sexo del alumno (M o F)");

        if(sexo == "F"){
            if(estatura>160 && peso>60){
            countF++;
            }
        }

        else{
            if(estatura>170 && peso>70){
            countM++;
            }
        }
    }
}

A: use sexo.equalsIgnoreCase("f"); instead of sexo=="f"
And add a check that user only inputs M or F else it would still do CountM++


text:
Q: Why X-ray and radio waves can penetrate walls but light can not? Why can visible light, which lies in the middle between X-ray and radio waves in terms of frequency/energy, not penetrate walls?

A: To understand what radio waves are, please read about What are photons, electromagnetic radiation and what are radio waves.
The thickness of a wall
You should have no problems with X-rays.
  The moment of such photons is simply strong enough to penetrate materials. Without interacting with the wall, they exit the wall with the same wavelength (I prefer to talk about the same energy, frequency and moment).
  Or they exit with a reduced energy due to absorption and re-emission with the subatomic particles. We observe the energy difference between the incoming and outgoing photons as an increase in temperature of the material.
With the right material (lead) or with the right thickness for any material you are able to capture X-rays inside the material. On the other hand, you are able to transmit visible light even through metal. It's all about thickness. Gold or aluminum can be made so thin that light can pass through it.
Reflection from surrounding obstacles vs. closed rooms
Take a spotlight with a wide lighting angle and point it at the wall. The surrounding reflective obstacles will cause the wall to be illuminated from the other side. A distant radio source is like a very large transmitter (spotlight). The surrounding obstacles also reflect the radio waves.
On the other hand, it is possible to build a closed room in which neither visible light nor radio waves can illuminate a wall inside the room.
In these cases everything revolves around the experimental setup.
The real difference
Radio waves have two properties that light from a thermal source does not have.
The photons of a radio wave are polarized. Every half period of the wave generator the influenced skin electrons change their direction of acceleration and emit photons with the electric field component up or down (in case of a vertical antenna rod). The radio wave is a polarized radiation.
Furthermore the radio wave is by its nature (technical concept) a radiation with periodic intensity.
These two properties could influence the material of a wall. Phonons are one way in which radio waves penetrate a wall with their "synchronized" photons. By analogy, take a hanging metal sheet and blow on it with a certain intensity. The sheet is lifted a little bit. If you do the same with the same energy content, but periodically with a higher intensity, the sheet can be resonated and periodically lifted so that more air gets behind the hanging sheet.
Periodicity and polarization - I am sure that these two properties of radar on surfaces should be suppressed in order to be successful in stealth technology.

Edit
Quote from Wikipedia about molecular oscillations from radio waves to heat:

One of the most commonly known types of RAM is iron ball paint. It contains tiny spheres coated with carbonyl iron or ferrite. Radar waves induce molecular oscillations from the alternating magnetic field in this paint, which leads to conversion of the radar energy into heat. The heat is then transferred to the aircraft and dissipated.

A: The interaction of photons with matter is complicated. The electromagnetic spectrum covers many orders of magnitude in frequency and photon energy, and there are qualitatively different processes that occur in different regimes. The results depend on the electrical properties of the material, such as conductivity and permittivity. We have materials like glass that are transparent to visible light, and low-energy x-rays that are strongly absorbed.
But speaking very broadly, it is possible to understand the main trends over the whole spectrum. We have a region (1) in the visible spectrum, where the frequency of the light is similar to the frequency of condensed-matter resonances, which in many cases you can think of as resonances of the electrons, as if the electrons are little objects attached to atoms by springs; and region (2) in low-energy x-rays, where the wavelength of the photon is comparable to the wavelength of the electrons in an atom. This splits up the spectrum into three parts.
At low frequencies $f$, below region 1, we have a skin depth, which depends on $f^{-1/2}$. As $f$ gets smaller, the skin depth grows without bound. Hence radio waves tend to be penetrating.
Around region 1, you get strong classical resonant behavior. You can see this if you look at a plot of the index of refraction of glass as a function of frequency. It has a series of spectacular peaks. Each of these peaks has a classic Lorentzian shape, in which the response on the right-hand side of the peak approaches zero. So if you ignore the peaks themselves, which are narrow, then you get a series of stair steps. At frequencies above region 1, you've gone down all the stair steps, and the response approaches zero. This is why, classically, we expect high-frequency electromagnetic radiation to interact with matter very weakly.
But in region 2 you get the photoelectric effect. In first-order perturbation theory, this depends on the extent to which the electric field overlaps with the wavefunction of the electron. When the two wavelengths are similar, you get a strong cross-section. This is why matter strongly absorbs soft x-rays, but not gammas and hard x-rays.

A: X rays penetrate matter because their energy is much higher that of any matter excitations. The electrons in matter are to slow and too heavy to react and compensate the field, as they do for optical frequencies. Fort radio wave the opposite applies. They reflect off matter, especially off metals, unless you apply very special coatings. By reflection and diffraction they can go around obstacles and pass through openings.


text:
Q: Which intel graphics firmware version is in use & how to change that On ubuntu 17.10, I installed recent Intel graphics firmware:
skl_dmc_ver1_26
skl_guc_ver6_1
skl_huc_ver01_07_1398

from https://01.org/linuxgraphics/downloads/firmware using the install.sh scripts. After upgrading to ubuntu 18.04, I noticed that the newer versions of this firmware are already in /lib/firmware/i915.
Now I am not sure which firmware versions are in use - old or new?
dmesg | grep skl_
returns ... skl_dmc_ver1_26.bin (v1.26)

*

*Does this mean that the old version is in use?

*What about guc and huc?

*How do I change it to the new version?

A: Short Answer
To change the drivers in use you need to change your kernel version. However you shouldn't do this unless there are specific reasons to do so.
Long Answer
The install.sh scripts have been deprecated and are no longer used. Now there are blobs (Binary Large Objects) that simply need to be downloaded and then copied to /lib/firmware/i915. If you follow the link you posted you will see it has been changed from the last time you downloaded.
For instructions on installing the new blobs see: Updated kernel to 4.8 now missing firmware warnings
As far as quickly seeing which i915 drivers for Skylake you have installed (but not necessarily active for current boot) use:
$ locate i915/skl_
/lib/firmware/i915/skl_dmc_ver1.bin
/lib/firmware/i915/skl_dmc_ver1_23.bin
/lib/firmware/i915/skl_dmc_ver1_26.bin
/lib/firmware/i915/skl_guc_ver1.bin
/lib/firmware/i915/skl_guc_ver1_1059.bin
/lib/firmware/i915/skl_guc_ver4.bin
/lib/firmware/i915/skl_guc_ver4_3.bin
/lib/firmware/i915/skl_guc_ver6.bin
/lib/firmware/i915/skl_guc_ver6_1.bin
/lib/firmware/i915/skl_guc_ver9_33.bin
/lib/firmware/i915/skl_huc_ver01_07_1398.bin

I noticed in your link a new version skl_dmc_ver1_27.bin so I downloaded it and then ran:
$ sudo updatedb
[sudo] password for rick:
───────────────────────────────────────────────────────────────────────────────────────────
rick@alien:~$ locate dmc_ver1_27
/home/rick/Downloads/skl_dmc_ver1_27.bin
───────────────────────────────────────────────────────────────────────────────────────────
rick@alien:~$ sudo mv /lib/firmware/i915/skl_dmc_ver1_26.bin /lib/firmware/i915/skl_dmc_ver1_26.bin.old
───────────────────────────────────────────────────────────────────────────────────────────
rick@alien:~$ sudo mv /home/rick/Downloads/skl_dmc_ver1_27.bin /lib/firmware/i915/skl_dmc_ver1_27.bin
───────────────────────────────────────────────────────────────────────────────────────────
rick@alien:~$ sudo update-initramfs -u -k `uname -r`
update-initramfs: Generating /boot/initrd.img-4.14.42-041442-generic
W: Possible missing firmware /lib/firmware/i915/skl_dmc_ver1_26.bin for module i915
Adding /lib/firmware/i915/skl_guc_ver9_33.bin

So even though skl_dmc_ver1_27.bin is available it doesn't work with the Kernel 4.14 chain and it still looks for skl_dmc_ver1_26.bin. Ubuntu 18.04 uses the 4.15 kernel chain so apparently it is using skl_dmc_ver1_26.bin as well.

I just downloaded Kernel 4.17 which came out two days ago and it uses the new skl_dmc_ver1_27.bin driver:
$ sudo mv /lib/firmware/i915/skl_dmc_ver1_27.bin /lib/firmware/i915/skl_dmc_ver1_27.bin.old
$ sudo update-initramfs -u -k 4.17.0-041700-generic
update-initramfs: Generating /boot/initrd.img-4.17.0-041700-generic
W: Possible missing firmware /lib/firmware/i915/skl_dmc_ver1_27.bin for module i915
W: Possible missing firmware /lib/firmware/i915/kbl_dmc_ver1_04.bin for module i915
W: Possible missing firmware /lib/firmware/i915/cnl_dmc_ver1_07.bin for module i915
W: Possible missing firmware /lib/firmware/i915/kbl_guc_ver9_39.bin for module i915
W: Possible missing firmware /lib/firmware/i915/bxt_guc_ver9_29.bin for module i915
Adding /lib/firmware/i915/skl_guc_ver9_33.bin

Notice how it's looking for /lib/firmware/i915/skl_dmc_ver1_27.bin

Summary

*

*Kernel 4.14 uses skl_dmc_ver1_26.bin.

*Kernel 4.17 uses skl_dmc_ver1_27.bin.

*/lib/firmware/i915/skl_guc_ver9_33.bin is used by both Kernels 4.14 and 4.17.

You also asked: "What about guc and huc?" guc is answered immediately above. As far as huc is concerned the same version is used from Kernel 4.14 (and earlier) to Kernel 4.17:
rick@alien:~/Downloads$ sudo mv /lib/firmware/i915/skl_huc_ver01_07_1398.bin /lib/firmware/i915/skl_huc_ver01_07_1398.bin.old
───────────────────────────────────────────────────────────────────────────────────────────
rick@alien:~/Downloads$ sudo update-initramfs -u -k `uname -r`
update-initramfs: Generating /boot/initrd.img-4.14.42-041442-generic
W: Possible missing firmware /lib/firmware/i915/skl_dmc_ver1_26.bin for module i915
W: Possible missing firmware /lib/firmware/i915/skl_huc_ver01_07_1398.bin for module i915
Adding /lib/firmware/i915/skl_guc_ver9_33.bin


text:
Q: Find the first point where a line touches a convex hull First I have ploted a convex hull for given points using convexHull Matlab function:
x = [4*rand(10,1)-2];
y = [rand(10,1)+5];
DT = delaunayTriangulation(x,y);
C = convexHull(DT);
plot(DT.Points(:,1),DT.Points(:,2),'.','MarkerSize',10)
hold on
plot(DT.Points(C,1),DT.Points(C,2),'r')

This convex hull is just an example, it can be any other convex hull. We assume that convex hull is inside parabola y=x^2.
Then I want to find first point on convex hull that touches line y=[(a^2+1)/a]x-1, when we start from a=1 and it can go until a=+\infty if never touches convex hull (when convex hull is on LHS).
How that can be accomplished? My final goal is to find a on the figure.

A: For each corner (x_i, y_i) of the polygon solve quadratic equation for a_i.
y_i*a_i = (a_i^2 + 1)*x_i - 1
You can obtain the equation by putting the point coordinates into the line equation. Next, discard solutions that are not relevant for You (a<1). Once this is done, sort solutions by a. If you also need the index of corresponding vertex, sort function in Matlab gives you indexing array as an additional output. You can then plot the line.
As a corner case, the line may hit two vertices. This is not a problem if you just need a. If you want the vertex id, just discard one arbitrarily, or use some additional rule.


text:
Q: Are these sentences grammatically correct in e-mail? Are these sentences grammatically correct in e-mail?

I saw your catalogue of 'Canadian Used Car & Truck Values' and I can't find my vehicle. Therefore, I have a question. How much is value of my car?
  -- Information of my car --

This information is sorely needed for me.

A: Close. Just add an article for "value" and double quotes unless you are already in a quotation.

I saw your catalogue of "Canadian Used Car & Truck Values" and I can't find my vehicle. Therefore, I have a question. How much is the value of my car?

BTW, "This information is sorely needed by me."

A:
[Greeting],
I saw your catalogue of "Canadian Used Car & Truck Values," but I
  wasn't able to find my vehicle. It's a [2002 AwesomeMobile]. Is there
  a listing for this vehicle that I missed? Could you please tell me the
  value of my car? I really need this information.

*

*Year: 2002

*Make: AwesomeMotors

*Model: AwesomeMobile

*Style: 2-door

*Mileage: 5.

  Thank you,
[Name]

For the most part the original would be understandable & fine, with minor alterations.
I changed "and" to "but" in the first sentence - you looked, but couldn't find it as expected. I also changed "can't find" to past tense. This works either way though.
I'd say there's no need to state that you have a question - it's obvious when you ask one.
Including the vehicle info in the body text is optional, but makes it clear up front what car you're looking for.
I would ask for the value and for help looking elsewhere for the information I need. Also, there may be a difference between "trade-in value" (to a dealer as part of buying a new car) and "resale value" if you want to sell it yourself.
"Sorely needed" sounds very British to me, so I personally wouldn't use that - perhaps it's a regional thing. I'd also suggest using an 'active' rather than 'passive' construction for that sentence:

"I really need this information" vs. "This information is really needed by me (sounds wrong)."

(Aside: if you really need the car value, you could check Kelley Blue Book online which is primarily for U.S. values, but you can check border areas near Canada).


text:
Q: VBA Outlook detect new email EDIT: The code below works if anyone wants to use it. Just make sure to save your changes and restart outlook. Because that was my issue.
I've found many resources that explain how to trigger an event when a new email is received in outlook, but for whatever reason I can't get the initialization to work. Below is the the code I'm using. Debug.Print does not print and it doesn't seem like this runs at all. I'm getting no feedback from the system so I'm having trouble troubleshooting this. Any thoughts?
I've followed this YouTube video. Despite following the steps I'm not getting the same results. https://www.youtube.com/watch?v=5qcftHAWnZI
If it matters, I'm using Outlook 2013
Private WithEvents olItems As Outlook.Items

'On start up
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace

Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")

Set olItems = olNS.GetDefaultFolder(olFolderInbox).Items

Debug.Print "Application_Startup trigerred " & Now()

End Sub

'New email recieved
Private Sub olItems_ItemAdd(ByVal item As Object)

Dim my_olMail As Outlook.MailItem
Dim olAtt As Outlook.Attachment

If TypeName(item) = "MailItem" Then
    Set my_olMail = item

        Debug.Print my_olMail.Subject
        Debug.Print my_olMail.Attachments.Count
        Debug.Print my_olMail.SenderEmailAddress

    Set my_olMail = Nothing

End If

End Sub

A: I guess I'm dumb. All you need to do is save the changes and restart outlook again. smh


text:
Q: trouble with tripling letters I've been assigned with the task of writing a program that triples all the letters in a string (ex: triple("Hello") should output "HHHeeelllooo")
After some time being stuck on this:
def triple(s) :
    new = ""
    i = 0
    for l in s[i]:
        new += l * 3
        i += 1
    return new

I solved rewriting it like this, which works:
def triple(s):
    new = ""
    i = 0
    for i in range(len(s)):
        new += s[i]*3
    return new

but, even though I found a solution, it would be really important to me to understand why the first version doesn't work, in order to avoid being stuck again in the future.
Thank you in advance to anyone who's willing to help me understand what was wrong in my logic.


text:
Q: putParcelableArrayListExtra and black screen I have custom class that implements Parcelable and I use it as custom arraylist.
When I use putParcelableArrayListExtra and 400 rows it works fine, but 1000 rows it does not. I have black screen and app locks up. What is wrong?
EDIT:
I sent it here and I don't use it in another Activity.
Intent intent = new Intent().setClass(getApplicationContext(), ArtActivity.class);
intent.putParcelableArrayListExtra ("mylist", list);
startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);

My array:
ArrayList<Piece> list = new ArrayList<Piece>();

It is my Class:
public class Piece implements Parcelable {
    private String id;
    private String name;
    private int type;
    private String text;
    private String mp3;

   public Piece (String id,String name,int type)
   {
     this.id=id;
     this.name=name;
     this.type=type;
   }

   public Piece(Piece ele)
   {
      this.id=ele.id;
      this.name=ele.name;
      this.type=ele.type;
      this.text=ele.text;
   }

   public Piece (Parcel in)
   {
        id = in.readString ();
        name = in.readString ();
        type = in.readInt();
        text= in.readString();
        mp3=in.readString();
   }

   public static final Parcelable.Creator<Piece> CREATOR
   = new Parcelable.Creator<Piece>()
  {
        public Piece createFromParcel(Parcel in)
        {
            return new Piece(in);
        }

        public Piece[] newArray (int size)
        {
            return new Piece[size];
        }
   };

   public void makeText(String text)
   {
       this.text=text;
   }

   public void makeMp3(String mp3)
   {
     this.mp3= mp3;
   }

   public String getMp3()
   {
   return this.mp3;
   }

   public String getId()
   {
       return id;
   }
   public String getName()
   {
       return name;
   }
   public int getType()
   {
       return type;
   }
   public String getText()
   {
       return text;
   }

  public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
  }

  public void writeToParcel(Parcel dest, int flags) {
    // TODO Auto-generated method stub
    dest.writeString (id);
    dest.writeString (name);
    dest.writeInt(type);
    dest.writeString (text);
    dest.writeString (mp3);
  }
}

A: I do not believe you should be using parcelable in this case. I would either access the data statically (if you only intend to have one persistent instance of the data), or use a caching system to hold onto the data.
This is an example of a publicly available static variable:
public static List<Piece> list;

It is accessible from everywhere in your app that has visibility of the class.
However, doing this is very messy and is considered a bad practice. Alternatively, you can create an object to manage the data for you as a static class or singleton:
public class MyListManager {
    private static List<Piece> mList;

    public static List<Piece> getMyList() {
        return mList;
    }

    public static void setList(List<Piece> list) {
        mList = list;
    }
}

Alternatively, you can implement some kind of a caching system to manage your data.


text:
Q: SQL Server users and application users I have develop a web application in MVC4 it is a application about credit and financing. Application is used by 40 to 50 users at a time. Application reporting is very heavy takes 2 to 3 minutes in generating.
I am using single db user 'sa'
Now I am thinking to create all application users in server 2008 also.
Each application user will connect with own db user not with 'sa' user
my question is that is It right decision?
It will increase my application performance?  If it is not right then how i can increase its performance? as 40 users taking reports with single 'sa' user may be take more time instead off each user taking with its own database user.

A: First of all: DO NOT USE 'sa' account.
Create database roles for the application with appropriate permissions, reader, writer, executor etc, with only permissions the application requires.
Secondly, is there any reason this server is not on the Windows Domain? It is preferable to handle permissions via AD Security Groups and service accounts (and managed service accounts) rather than SQL accounts. The benefit is simplified management and increased security - Kerberos vs plain text passwords.
EDIT : as I have not answered your question. In your case the number of users is irreleveant as they transalate to number of requests and spawned workers/threads. You are asking database to serve 40 reports, no matter if they all come from 1 user, or 40 users asks for 1 report, the end result is still 40. In extreme situations it may be preferable to have less users to save resources and time on creating new connections as each takes tiny amount of memory but that is a whole different conversation.
Hope this helps.

A: 100% agree with Marcin Gminski.  The SA account is definitely not supposed to be used this way.  Windows domain credentials certainly are preferable although not necessary.  If you are going to use a single login account for all users, at least create a new login that is not a part of the System Admin role and make sure it has a strong password.
As for your performance issue, we would need to know more.  First off, what is your method used for data access in the MVC app.  Are you using Entity Framework, Linq or something else?  Next, have you debugged the app to see if it is making excessive, unnecessary calls to the database.  Next, have you attempted to run a SQL Profiler trace to capture the activity on the server?  Those steps should at least provide a little more insight in to where the problem exists.


text:
Q: How to use data() as a function argument How can I write a function that takes an argument which is passed to the data function in R.
As a simple example
load_data <- function(mydata) {
    x <- data(mydata)
    x
}

If I tried to use this to load iris
load_data(mydata = "iris")

The function just returns "data set mydata not found"
My end goal here is to have a function that attaches a dataset to the function's environment, and then the function would do some arbitrary calculations.

A: If you want data() to evaualte that character string, it needs to be passed via list=
load_data <- function(mydata) {
  x <- data(list=mydata)
  x
}

I'm not sure what you were expecting to be returned but the ?data help page tells you it just returns the name of the data sets loaded, not the data itself.
If you only want it to load into the function scope, then also set the environment= parameter
load_data <- function(mydata) {
  data(list=mydata, environment=environment())
}

A: If you want iris to be stored in x then you don't need to call data at all.
load_data <- function(mydata) {
  x <- mydata
  x
}

load_data(iris)


text:
Q: Dual NIC Windows 7 on LAN with seperate DNS I have a Windows 7 machine with two NICs and that sits on two LANs (neither is connected to the internet).
On one LAN the DNS seems to work just fine, I am able to reach other computers on that LAN via computer name. However, I can't reach machines on the second LAN via name, but IP address does work.
Is there a way to set it up so Windows 7 is able to reach computers on both networks via name?
After some investigation it seems that the DNS server on the second network doesn't respond.  I do a nslookup computername DNS-IP  (replacing the two options with a computer on the network and the ip of the DNS) and I get a timeout.  I can ping the DNS computer, so I can talk to it but it won't respond to the DNS request.  The same command on a computer just on the second network works as expected (returning the DNS info).
Both LANs have their own domain controller.  I login to Windows using the first network's domain controller, could the second network (the one I can't get DNS from) be causing problems becuase I am not logged in to there domain controller?

A: It sounds like DNS is not properly configures on one of the two NICs.

*

*Open the Control Panel

*Type Network and Sharing in the upper right hand corner search box and hit Enter

*Click Change Adapter Settings

*Right click on the network adapter you are having issues with and click Properties.  If you don't know which one is the problem, you might have to look at the properties for both and deduce which is the NIC with the DNS issue

*Select Internet Protocol Version 4 (TCP/IPv4) and click the Properties button

*The bottom box of the Properties shows DNS information.  If you receive your IP automatically from a DHCP server (top box of dialog), then more than likely, you should use Obtain DNS server address automatically.  However, if you do not, select the opther option, Use the follwing DNS server addresses and enter in the preferred and alternate DNS server address.


text:
Q: How to query dynamo-db with primary and global secondary index I have this dynamodb query:
var unitsData = await(docClient.query({
                TableName:"test-units-" + config.stage,
                IndexName:"unitOwnerIndexDev",
                KeyConditionExpression : 'ownerName= :hkey',
                ExpressionAttributeValues : {
                    ':hkey': event.ownerName
                },
                Key:{"unitID": event.unitID
                }
            }).promise());

I am expecting it to return only one row with unique unitID and its owner. But returned data isn't unique with respect to unitID. It does filter out with respect to owner. unitID is primary key (HASH) and owner is global secondary index.
This is my table:
aws dynamodb create-table --table-name test-units-dev --attribute-definitions AttributeName=unitID,AttributeType=S AttributeName=ownerName,AttributeType=S --key-schema AttributeName=unitID,KeyType=HASH --global-secondary-indexes IndexName=unitOwnerIndexDev,KeySchema=["{AttributeName=ownerName,KeyType=HASH}"],Projection="{ProjectionType=ALL}",ProvisionedThroughput="{ReadCapacityUnits=1,WriteCapacityUnits=1}" --provisioned-throughput ReadCapacityUnits=1,WriteCapacityUnits=1 --endpoint-url http://localhost:8000

A: Please use FilterExpression to filter the data by non-key attributes. In the above case, unitID is not part of key in GSI.
The below params works fine for me (i.e. the result has only one item).
var params = {
    TableName : table,
    IndexName : "unitOwnerIndexDev",
    KeyConditionExpression : 'ownerName= :hkey',
    FilterExpression : 'unitID = :unitIdVal',
    ExpressionAttributeValues : {
        ':hkey' : 'owner1',
        ':unitIdVal' : '1'
    }
};


text:
Q: Preselection of probability for approximate string matching I have recently been tasked with developing an algorithm for checking for duplicate customer records in a database.
The DB layout is pretty straightforward: Tens of thousands of rows with fields like FullName, Street, City, ZIP, Phone, etc...
A little background first:
I have done some extensive research on algorithms, and have decided that every field should be weighed at a certain amount
with different algorithms, since not all perform equally well under all circumstances.
For example, LastName has a weight factor of 0.50. When I evaluate I choose which algorithms to use and how much they weigh on the final decision:
Factor 0.25: JaroWinkler
Factor 0.60: Cosine 2-Gram Similarity
Factor 0.15: DamerauLevenshtein
Everything works well, and with a little tuning I detect the positives with little error.
So far so good. However, as you can imagine, having a runtime of O(n^2) - or actually E form i=0 to i=n - is not very effective when dealing with tens of thousands of records.
Needless to say that optimizing aggressively, using compiler optimizations for speed, multithreading, etc, are just bandaids since the real problem is the complexity.
Essentially, I am looking for a way to pre-filter the potential matches, and have done three days of research on this now.
I have found some valuable information on R-Trees, R*-Trees, KD-Trees, Eucledian vectors, minhashing, et al.
However, most information about all these is, well, rather highly academic. The most valuable resource I found was in "Mining Massive Data Sets", Chapter 3.
Now to my real question:
I've read all this information, but I'm not sure how to put it all together.
I was thinking about some sort of indexing in a tree or graph data structure where I can putin a string and say "Find me all that have a probability of matching > 0.20".
This algorithm should be really fast. Then, when I get a list of potential (>0.20) matches, I could go and compare the few items with my "expensive", but selective algorithm.
That should cut the runtime to a very reasonable value I believe.
I have been trying to find some sort of reference code to do what I want to do above, but I don't seem to come up with anything other than scholarly articles.
I did find "simstring", which actually compiled, but didn't seem to match 7 test records very well..
Could anyone point me in the right direction? Surely someone must have run into this before and found a solution...
Thank you very much in advance!
P.S. I am doing this in C++, but any samples in C#/C/Java/PHP would be fine.

A: As a first cut at this, I'd simply select those strings close enough to the same length that they could match to within the given probability. This won't be very selective, but (unless you specify quite loose tolerances) will probably eliminate quite a large percentage of impossible matches very quickly. (e.g., with an edit metric like Levenshtein that counts an insertion as 1 operation, if you start with a string of length 5 and a need to match within 5 operations, then you can eliminate all strings longer than 10 without further examination).
Whether this will be selective enough to go straight to your expensive comparison is open to question -- obviously that'll depend on the variability of the lengths of strings you're matching against.

A: I ahve finally succeeded in implementing a preselection by doing the following:
1. Use certain fields of the customer record to construct 2Grams
2. Minhash the 2Grams with a familiy of 6 minhash functions to a 192 bit signature
3. Use the boost::geometry libraries' rtree implementation to create a 6 dimensional spatial index over the signatures
4. Select the nearest k (im my case 30) records for the record I'm comparing and on those candidates run the original "expensive" comparison
5. This reduces the complexity from E(i,i=n,i=1) to roughly 30n + m, where m is the time it takes to build the index (almost negligible, surprisingly).
I can run 15,000 comparisons with high accuracy in 60 seconds now, and that is in a single-threaded test. Multithreaded to 4 or 8 cores this will run even faster.


text:
Q: Gurobi: Unable to convert argument to an expression I'm kinda new to gurobi on python
Is there someone who can explain me what I'm doing wrong?
I get the error :

gurobipy.GurobiError: Unable to convert argument to an expression

when I call :

m.setObjective(obj,GRB.MINIMIZE)

My code:
m = Model("mdp")

v=[]
for i in range(nblignes):
    for j in range(nbcolonnes):
        v.append(m.addVar(vtype=GRB.CONTINUOUS, lb=0, name="v%d" % (i*10+j)))

m.update()

c=np.zeros((len(v),1), dtype=numpy.int)
for k in range(len(v)):
    c[k]= 1

obj = LinExpr();
obj =0
for j in range(nbcolonnes*nblignes):
    obj += c[j] * v[j]
print "OBJ",obj

m.setObjective(obj,GRB.MINIMIZE)

A: Your array 'c' is a len(v) x 1 matrix, so when you add c[j] * v[j], you multiply a vector by an gurobi Var object.  You can fix this by either declaring the array as 1-D with
c=np.zeros(len(v), dtype=numpy.int)

or replacing your final loop with
for j in range(nbcolonnes*nblignes):
     obj += c[j][0] * v[j]

or more succinctly
obj = quicksum(c[:,0]*v)


text:
Q: Spring WS: How to apply Interceptor to a specific endpoint I have multiple working SOAP Web Services on a Spring application, using httpBasic authentication, and I need to use WS-Security instead on one of them to allow authentication with the following Soap Header.
<soap:Header><wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soap:mustUnderstand="1">
  <wsse:UsernameToken xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="UsernameToken-1">
    <wsse:Username>username</wsse:Username>
    <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">password</wsse:Password>
  </wsse:UsernameToken>
</wsse:Security></soap:Header>

Current WSConfiguration was done according to https://github.com/spring-projects/spring-boot/blob/master/spring-boot-samples/spring-boot-sample-ws/ giving something like
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

    @Bean
    public ServletRegistrationBean dispatcherServlet(ApplicationContext applicationContext) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(applicationContext);
        return new ServletRegistrationBean(servlet, "/services/*");
    }

    @Bean(name = "SOAP1")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema soap1) {
        DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
        wsdl11Definition.setPortTypeName("Soap1");
        wsdl11Definition.setLocationUri("/soap1/");
        wsdl11Definition.setTargetNamespace("http://mycompany.com/hr/definitions");
        wsdl11Definition.setSchema(soap1);
        return wsdl11Definition;
    }

    @Bean
    public XsdSchema soap1() {
        return new SimpleXsdSchema(new ClassPathResource("META-INF/schemas/hr.xsd"));
    }

}

and Web Security according to http://spring.io/blog/2013/07/03/spring-security-java-config-preview-web-security/ looks like this
@EnableWebSecurity
@Configuration
public class CustomWebSecurityConfigurerAdapter extends
   WebSecurityConfigurerAdapter {
  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) {
    auth
      .inMemoryAuthentication()
        .withUser("user1")
          .password("password")
          .roles("SOAP1")
          .and()
        .withUser("user2")
          .password("password")
          .roles("SOAP2");
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeUrls()
        .antMatchers("/soap/soap1").hasRole("SOAP1")
        .antMatchers("/soap/soap2").hasRole("SOAP2")
        .anyRequest().authenticated()
        .and().httpBasic();
  }
}

After some searches, I found that Wss4J provides a UsernameToken authentication, but can't figure out how to use it. What I'm trying to do is the following
https://sites.google.com/site/ddmwsst/ws-security-impl/ws-security-with-usernametoken
but without XML files with bean definitions.
What I plan to do:

*

*Create the Callback Handler.

*Create a Wss4jSecurityInterceptor, setting "setValidationActions" to "UsernameToken", "setValidationCallbackHandler" to my callback handler, and then add it by overriding addInterceptors on my WebServiceConfig.

(I tried something like that, but I just realised my callback was using a deprecated method)
Problem : Even if it works, it would then apply to all my webservices on "WebServiceConfig".
Update :
The implementation does work, but as expected it is applied to all my Web Services. How could I add my interceptor only to 1 Web Service ?
Following, the code I added in WebServiceConfig
 @Bean
    public Wss4jSecurityInterceptor wss4jSecurityInterceptor() throws IOException, Exception{
        Wss4jSecurityInterceptor interceptor = new Wss4jSecurityInterceptor();
        interceptor.setValidationActions("UsernameToken");
        interceptor.setValidationCallbackHandler(new Wss4jSecurityCallbackImpl());

    return interceptor;
}

@Override
public void addInterceptors(List<EndpointInterceptor> interceptors)  {
    try {
        interceptors.add(wss4jSecurityInterceptor());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

A: It is worthworthy to note that whether is the result of the method shouldIntercept, the program would execute anyways the handleRequest method.

This can be dangerous, for example, in the login process.

In a project that I'm developing, we have only two endpoints:

*

*UserLoginEndpoint

*SomeGeneralEndpoint

The login would be invoked only for logging in purposes and will produce a token that I'll have to parse somehow from the request (this is done via an interceptor, the only one that we need in the application).
 Suppose we have the following interceptor, just like Christophe Douy proposed and that our class of interest would be the UserLoginEndpoint.class
public class CustomSmartEndpointInterceptor extends Wss4jSecurityInterceptor implements SmartEndpointInterceptor {

//CustomEndpoint is your @Endpoint class
@Override
public boolean shouldIntercept(MessageContext messageContext, Object endpoint) {
    if (endpoint instanceof MethodEndpoint) {
        MethodEndpoint methodEndpoint = (MethodEndpoint)endpoint;
        return methodEndpoint.getMethod().getDeclaringClass() == UserLoginEndpoint.class;
    }
    return false;
}

If this returns true, by all means, that's good and the logic defined in the handleRequest method will be executed.
But where's my issue?

For my specific problem, I'm writing an interceptor that should get in the way only if the user has already logged in. This means that the previous snippet code should be the following
public class CustomSmartEndpointInterceptor extends Wss4jSecurityInterceptor implements SmartEndpointInterceptor {

//CustomEndpoint is your @Endpoint class
@Override
public boolean shouldIntercept(MessageContext messageContext, Object endpoint) {
    if (endpoint instanceof MethodEndpoint) {
        MethodEndpoint methodEndpoint = (MethodEndpoint)endpoint;
        return methodEndpoint.getMethod().getDeclaringClass() != UserLoginEndpoint.class;
    }
    return false;
}

And if that would be true, the handleRequest method would be executed (my implementation is below)
@Override
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {

    System.out.println("### SOAP REQUEST ###");

    InputStream is = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    Document doc = null;
    try {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        messageContext.getRequest().writeTo(buffer);
        String payload = buffer.toString(java.nio.charset.StandardCharsets.UTF_8.name());
        System.out.println(payload);
        is = new ByteArrayInputStream(payload.getBytes());
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(is);
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    }

    XPath xpath = XPathFactory.newInstance().newXPath();
    xpath.setNamespaceContext(new NamespaceContext() {
        @Override
        public String getNamespaceURI(String prefix) {
            switch(prefix) {
                case "soapenv":
                    return "http://schemas.xmlsoap.org/soap/envelope/";
                case "it":
                    return "some.fancy.ws";
                default:
                    return null;
            }
        }

        @Override
        public String getPrefix(String namespaceURI) {
            return null;
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return null;
        }
    });
    XPathExpression expr = xpath.compile("//*//it:accessToken//text()");
    Object result = expr.evaluate(doc, XPathConstants.NODE);
    Node node = (Node) result;
    String token = node.getNodeValue();
    return authUtility.checkTokenIsValid(token);

}

But what happens if shouldIntercept returns false? If the handleRequest method, which is mandatory to implement if you "implements" SmartPointEndPointInterceptor, returns true, the invocation chain will keep on; but if it returns false, it will stop there: I'm in the second case, but the handleRequest still gets executed.

The only workaround that I found is to add a property in the MessageContext which has an arbitrary key and a corresponding value which is the one returned from the shouldIntercept method.

Then negate that value in the very first lines of your handleRequest's implementation to force the return true and have the invocation chain
    if (!(Boolean)messageContext.getProperty("shouldFollow")) {
        return true;
    }

Of course, this will work in projects where only one interceptor is needed (i.e., in my case just to verify if the user is really logged in) and there are many other factors that might influence everything but I felt it was worthy to share in this topic.

I apologize in advance if I made a mistake in answering here instead of opening a new question

A: Sorry, I totally forgot to answer this, but in case it helps someone :
We got it working by creating a new SmartEndpointInterceptor, and applying it only to our endpoint:
public class CustomSmartEndpointInterceptor extends Wss4jSecurityInterceptor implements SmartEndpointInterceptor {

    //CustomEndpoint is your @Endpoint class
    @Override
    public boolean shouldIntercept(MessageContext messageContext, Object endpoint) {
        if (endpoint instanceof MethodEndpoint) {
            MethodEndpoint methodEndpoint = (MethodEndpoint)endpoint;
            return methodEndpoint.getMethod().getDeclaringClass() == CustomEndpoint.class;
        }
        return false;
    }
}

instead of adding a wss4j bean to the WebServiceConfig, we added our SmartEndpointInterceptor :
@Configuration
public class SoapWebServiceConfig extends WsConfigurationSupport {

    //Wss4jSecurityCallbackImpl refers to an implementation of https://sites.google.com/site/ddmwsst/ws-security-impl/ws-security-with-usernametoken
    @Bean
    public CustomSmartEndpointInterceptor customSmartEndpointInterceptor() {
        CustomSmartEndpointInterceptor customSmartEndpointInterceptor = new CustomSmartEndpointInterceptor();
        customSmartEndpointInterceptor.setValidationActions("UsernameToken");
        customSmartEndpointInterceptor.setValidationCallbackHandler(new Wss4jSecurityCallbackImpl(login, pwd));
        return customSmartEndpointInterceptor;
    }

  [...]
}

Hope this is clear enough :)


text:
Q: $\int_{\mathbb R^n}e^{{-|x|}^n}dx$ I'm trying to prove that $\int_{\mathbb R^n}e^{{-|x|}^n}dx = V(B_{n}(0,1))$ using induction and Cavalieri's principle.
Notice that $\int_{\mathbb R} e^{-|x|}dx = 2 = V(B_1(0, 1))$ so the basis of our induction is true.
Now suppose that for some $k-1$ we have $\int_{\mathbb R^{k-1}}e^{{-|x|}^{k-1}}dx = V(B_{k-1}(0,1))$
We want to calculate $\int_{\mathbb R^{k}}e^{-{|x|}^{k}}dx$, we can choose to extract it by spheres since this is a positive function, so this will be equal to $$\lim_{r \to \infty}\int_{x_1^2+\dots x_k^2 \leq r^2}e^{-|x|^{k}}dx.$$
Consider the intersection of this sphere with the plane $x_k = t$. From Cavalieri's principle:
$$
\int_{x_1^2+\dots x_k^2 \leq r^2} e^{-|x|^{k}}dx
= \int_{-r}^r
  \left( \int_{x_1^2+\dots+x_{k-1}^2 \leq r^2-t^2}
              e^{-(x_1^2+\dots+x_{k-1}^2+t^2)^{k/2}}dx_1dx_2\dots dx_{k-1}
  \right) dt$$
Not sure where to go from here....

A: I think Cavalieri's principle means this way:
$$
\int_{\Bbb R^n}e^{-|x|^n}\mathrm dx =\int_0^1 \text{vol}\{x:e^{-|x|^n}\ge t\}\mathrm dt.
$$ (Explanation: imagine we are given $z=e^{-x^2-y^2}$. We can calculate the volume under the graph by cutting it along $z=t\in (0,1)$, calculating the area of the cross-section and re-gathering it.) This gives
$$\begin{eqnarray}
\int_0^1 \text{vol}\{x:e^{-|x|^n}\ge t\}\mathrm dt&=& \int_0^1 \text{vol}\left[(-\ln t)^{\frac{1}{n}}\cdot B_n\right]\mathrm dt\\&=&\text{vol}(B_n) \int_0^1 (-\ln t)\mathrm dt\\&=&\text{vol}(B_n),
\end{eqnarray}$$where $B_n$ is a $n$-dimensional unit ball and $c\cdot B_n = \{cx\;|\;x\in B_n\}=B_n(0,c)$.


text:
Q: How to move a record from one collection to another collection using mongoose Tried to move a record from one collection to another collection in mongodb using mongoose. But not working.I do not know to do it. I am new in mongoose.If anyone know please help me.
Getting error Like:

DocumentNotFoundError: No document found for query "{ _id:
  5ed6407d511657149c4ad65d }" on model "Xyz"

data.controller.js:
module.exports.movearecordToAnother = (req, res, next) => {
let from= req.query.delete;
let to= req.query.push;
let invoiceno = req.query.invoice;

mongoose.model(from).findOne({ invoice: invoiceno }, function(err, result) {

    if (err) {
        console.log(err);
        return;
    } else {
        let swap = new(mongoose.model(to))(result);
        //swap._id = mongoose.Types.ObjectId();
        //swap.isNew = true
        result.remove();
        swap.save();
        console.log("Successful moved");
        res.json({ data: result, success: true, msg: 'Successful moved a record.' });

    }
});
};


text:
Q: Providing user login support on web for my application  I have a background in android development with almost no knowledge of server side implementations. I want to create an application wherein I can store user's data on the cloud (for example: user's call log or periodic gps location). I have had a look at parse.com features and it comes pretty close to what I need. Its especially attractive because of its ease of use and good documentation.
However, I need to provide the user access to this data from a web service as well (suppose the user doesn't have access to his/her phone). For this I need to create a user login support on my parse application page. Is it even possible to do that?
Also, I want to run some analysis on this data and present the user with this analysis through this online account.
Are there any other backend frameworks which can help me achieve this quickly?

A: The JavaScript SDK is officially supported by Parse, so you could not go wrong choosing that. However, if you'd like a server-side framework, check out the 3rd party libraries for the REST API. Depending on your language preference, you should find something suitable to your needs there.
EDIT: You can also use the JavaScript SDK on the server with Node.js: http://blog.parse.com/2012/10/11/the-javascript-sdk-in-node-js/

A: You can use Parse for this. Parse provides both a REST API and a JavaScript SDK which you can use to create a companion web site for your mobile app.


text:
Q: Прочитать большой файл не сжирая память Есть огромный файл коротких строчек (URLов). База где-то на 20 мега байт. Обычный хостер будет бить если я начну при каждом запросе читать файл и отдавать одну случайную строчку из жирного файла.
Как прочитать случайную строчку из огромного файла не сжирая кучу памяти ?
A: $fp     = fopen($filename, 'r');
$offset = mt_rand(0, filesize($filename) - 1);
fseek($fp, $offset);

// пока не встретится перенос строки или начало файла
while ($offset > 0 && fgetc($fp) != "\n") {
    fseek($fp, --$offset);
}

$line = fgets($fp);

A: $avg_line_len = 30; // Средняя длинна строки
$file = fopen("list-url.txt", "r");
if ($file !== FALSE) {
    $stat = fstat( $file );
    do {
        do {
            $post = rand( 0, $stat['size'] - $avg_line_len );
        } while( fseek($file, $pos) == -1 );
        fgets($file); // Первый раз читаем до первого \n,
                      // так как можем попасть в середину строки
    } while( ($url = fgets($file)) == FALSE);
    // $url - случайная строчка из файла
}

P.S.
При большом размере файла (в исходной задаче несколько мегабайт) значением $avg_line_len можно пренебречь, а вместо fstat использовать filesize - результат будет тот-же самый
A: Предлагаю более простое решение. Сам файл нужно разбить на десяток(два) поменьше. Дальше, пусть в начальном файле было 100000 строк, а файлов 100 штук. Даем им имена вида "file00.txt","file01.txt" ... "file99.txt". С помощью rand(0,100); выбираем имя файла, а rand(0,1000); - строку. Дальше - так как приведено в других ответах.
Но главное не сильно увлекаться. 1000 файлов в одном каталоге уже будет подтормаживать. Поэтому нужно экспериментировать. Может будет смысл создать 10 каталогов с именами 0 - 9, и  туда положить по 100 файлов, в каждом по 100 строк.
Если кол-во строк не расскладывается на части оптимально, можно либо дублировать часть строк, либо обрабатывать кол-во строк в файле.
UPD:
Родился ещё один вариант, который может дать сильный прирост. Но для этого нужно будет подготовить файл для начала. Алгоритм такой. Проходим по всему файлу, находим самый длинный урл. Зная его длину, делаем новый файл, у которого каждая строка дополнена пробелами до нужной длины. Теперь, что бы перейти к нужной строке, нужно просто сделать fseek - fseek(номер_строки*(длина_строки) + 1)). Где 1 - это учет перевода строки (хотя нужно посмотреть, под виндой может быть 2). А после fseek можно читать данные.
A: $rand_line_number = rand(0,1000);
$handle = @fopen("file.txt", "r");
if ($handle) {
    $i = 0;
    while (($buffer = fgets($handle, 4096)) !== false) {
        if($i==$rand_line_number){
            echo $buffer;
            break;
        }
        $i++;

    }
    if (!feof($handle)) {
        echo "Ошибка чтения файла\n";
    }
    fclose($handle);
}

A: Перегони весь этот "огромный" файл в БД, и вытаскивай из БД. Если боишься перегонять это все дело на хосте, сделай на локалке, а потом залей базу на хост.
A: function fileRandLine($file)
{
    $res = '';

    if (is_file($file)) {
        $filesize = filesize($file);
        if ($filesize > 0) {
            $fp = @fopen($file, 'rt');
            if (is_resource($fp)) {
                for ($i = 0; $str = fgets($fp, $filesize + 1); $i++) {
                    if (mt_rand(0, $i) == 0) {
                        $trim = trim($str);
                        if (empty($trim)) {
                            $i--;
                            continue;
                        }
                        $res = $trim;

                    }
                }
            }
        }
    }

    return $res;
}

Применение:
echo fileRandLine('file.txt');


text:
Q: How to create Excel file with EPPlus for A4 paper My current project use EPPlus to create Excel files. These files are printed by the user and I'm trying to force the Excel file to print in only one A4 page, regardless the width og the content.
Actually, when the file is printed, it takes two pages and the second contains just one column.
My code:
ws.PrinterSettings.Orientation = eOrientation.Landscape;
ws.PrinterSettings.PrintArea = ws.Cells[ws_dimension_adress];
ws.PrinterSettings.TopMargin= 0;
ws.PrinterSettings.RightMargin = 0;
ws.PrinterSettings.BottomMargin = 0;
ws.PrinterSettings.LeftMargin = 0;
ws.Cells[ws_dimension_adress].AutoFitColumns();
ws.Cells[ws_dimension_adress].Style.Font.Size = 9;

The result:
The result provided by my code

What I need:

I searched things like "autofit to A4 page", eso but no solution yet.
Remark: all the columns are needed. I can't simply delete one before creating the file.
Thanks for helping!

A: I found the solution.
EPPlus has a printerSettings for this.
The line to use is
ws.PrinterSettings.FitToPage = true;

By using this, the default files properties force Excel to print the data in only one page.
Hope this help some other devs.

A: You can also use this line of code for a specific paper size:
ws.PrinterSettings.PaperSize = ePaperSize.A4;

Hopte this helps some others people.


text:
Q: Non AJAX alternative for mobile phones I am currently working on a forum and using a lot of raw AJAX in it for things like showing new threads, adding new thread, new comment, login, watching profile overview etc. But low bandwidth mobile connection create a mess out of the AJAX. So I would like to have a non AJAX solution for mobile devices. Since I already have the AJAX solution written modularly, how can I add this new functionality without losing the modularity? Thank you.

A: As you've probably seen, many sites have a separate "mobile" version of their interfaces, usually via m.<somesite>.com (m.facebook.com, m.twitter.com, etc.). Whether or not they make use of AJAX is another question, the important part is that you should be designing a separate interface for your mobile clients.
You may choose to disable AJAX for the mobile version of the site for bandwidth/responsiveness reasons, and if you do, the "modularity" of your existing AJAX code won't matter. Since your interface will be completely different (different CSS, [potentially] different markup), the modularity would be contained in the business logic of your app, not the client side html/css. Remember, this is if you use no AJAX (and probably very little JS at all) for your mobile site.
If you do plan on keeping AJAX around for the mobile devices, it's hard to tell you without seeing any design or code "how" to keep things modular. It depends very much on what your code actually looks like. However, it doesn't really seem as though your question is specific to AJAX methodologies.


text:
Q: Loading custom page template via plugin I am following a rather outdated tutorial on custom post types and the last step is to create a custom page template, where this is intended to show all posts of the custom type in archive listing format. As per the comments, the methods used no longer work 6 years later (go figure) and my custom page template isn't an option when creating a new page.
If I place my custom template in the theme folder it works but the option to load it from within the plugin directory has broken. How can I fix this so I can assign the template to a new page?
Edit
As I better understand now, this code is only loading the template when viewing my custom post types. The confusion was due to it showing as an available template on the "Page Attributes" section when it was located in the Themes directory. I am wanting to have it available as an option when making a new page, but have the template file located in my plugin's directory.
The original code from the tutorial:
add_filter( 'template_include', 'include_template_function', 1 );

function include_template_function( $template_path ) {
    if ( get_post_type() == 'movie_reviews' ) {
        if ( is_single() ) {
            // checks if the file exists in the theme first,
            // otherwise serve the file from the plugin
            if ( $theme_file = locate_template( array ( 'single-movie_reviews.php' ) ) ) {
                $template_path = $theme_file;
            } else {
                $template_path = plugin_dir_path( __FILE__ ) . '/single-movie_reviews.php';
            }
        }
    }
    return $template_path;
}

A: To add custom template in page attributes template section you have to first add your template to dropdown and load it in template_include hook when current page has selected it as current template.
/**
 * Add "Custom" template to page attirbute template section.
 */
function wpse_288589_add_template_to_select( $post_templates, $wp_theme, $post, $post_type ) {

    // Add custom template named template-custom.php to select dropdown
    $post_templates['template-custom.php'] = __('Custom');

    return $post_templates;
}

add_filter( 'theme_page_templates', 'wpse_288589_add_template_to_select', 10, 4 );

/**
 * Check if current page has our custom template. Try to load
 * template from theme directory and if not exist load it
 * from root plugin directory.
 */
function wpse_288589_load_plugin_template( $template ) {

    if(  get_page_template_slug() === 'template-custom.php' ) {

        if ( $theme_file = locate_template( array( 'template-custom.php' ) ) ) {
            $template = $theme_file;
        } else {
            $template = plugin_dir_path( __FILE__ ) . 'template-custom.php';
        }
    }

    if($template == '') {
        throw new \Exception('No template found');
    }

    return $template;
}

add_filter( 'template_include', 'wpse_288589_load_plugin_template' );

theme_page_templates hook is available for page post type. If you want to add custom template to other post type you must replace page with your custom post type name e.g. event post type hook will have a name theme_event_templates.