text:
Q: How to pass arguments to main function within Python module? I have recently started learning more about Python Packages and Modules. I'm currently busy updating my existing modules so that that can be run as script or imported as a module into my other code. I'm not sure how to construct my input arguments within my module and pass them to the main() function within my module.
I've have written my my main() function and called it under if __name__ == '__main__' passing the input arguments. The inputs are currently hard coded to show what I'm trying to achieve. Any help in how to correctly construct my input arguments that the user will pass, which will then be passed onto the main function will be appreciated.
As mentioned I'm trying to be able to use the following as a script when used directly or imported as a module into my other code and run from there. If I import it as a module would I call the main() function when importing it? Is the following structure correct in how I have written the following? Any advice is appreciated.
'''
Created on March 12, 2017

Create a new ArcHydro Schema

File Geodatabase and Rasters

Folder

@author: PeterW
'''
# import site-packages and modules
import re
from pathlib import Path
import arcpy

# set environment settings
arcpy.env.overwriteOutput = True

def archydro_rasters_folder(workspace):
    """Create rasters folder directory
    if it doens't already exist"""
    model_name = Path(workspace).name
    layers_name = re.sub(r"\D+", "Layers", model_name)
    layers_folder = Path(workspace, layers_name)
    if layers_folder.exists():
        arcpy.AddMessage("Rasters folder: {0} exists".format(layers_name))
    else:
        layers_folder.mkdir(parents=True)
        arcpy.AddMessage("Rasters folder {0} created".format(layers_name))

def archydro_fgdb_schema(workspace, schema, dem):
    """Create file geodatabase using XML
    schema and set coordinate system based
    on input DEM if it doesn't already exist"""
    model_name = Path(workspace).name
    fgdb = "{0}.gdb".format(model_name)
    if arcpy.Exists(str(Path(workspace, fgdb))):
        arcpy.AddMessage("{0} file geodatabase exists".format(fgdb))
    else:
        new_fgdb = arcpy.CreateFileGDB_management(str(workspace), fgdb)
        import_type = "SCHEMA_ONLY"
        config_keyword = "DEFAULTS"
        arcpy.AddMessage("New {0} file geodatabase created".format(fgdb))
        arcpy.ImportXMLWorkspaceDocument_management(new_fgdb, schema,
                                                    import_type,
                                                    config_keyword)
        arcpy.AddMessage("ArcHydro schema imported")
        projection = arcpy.Describe(dem).spatialReference
        projection_name = projection.PCSName
        feature_dataset = Path(workspace, fgdb, "Layers")
        arcpy.DefineProjection_management(str(feature_dataset),
                                          projection)
        arcpy.AddMessage("Changed projection to {0}".format(projection_name))

def main(workspace, dem, schema):
    """main function to create rasters folder
    and file geodatabase"""
    archydro_rasters_folder(workspace)
    archydro_fgdb_schema(schema, dem, workspace)

if __name__ == '__main__':
    main(workspace = r"E:\Projects\2016\01_Bertrand_Small_Projects\G113268\ArcHydro\Model04",
         dem = r"E:\Projects\2016\01_Bertrand_Small_Projects\G113268\ArcHydro\DEM2\raw",
         schema = r"E:\Python\Masters\Schema\ESRI_UC12\ModelBuilder\Schema\Model01.xml")

Updated: 17/03/13
The following is my updated Python module based on Jonathan's suggestions:
'''
Created on March 12, 2017

Create a new ArcHydro Schema

File Geodatabase and Rasters

Folder

@author: PeterW
'''
# import site-packages and modules
import re
from pathlib import Path
import arcpy
import argparse

# set environment settings
arcpy.env.overwriteOutput = True

def rasters_directory(workspace):
    """Create rasters folder directory
    if it doens't already exist"""
    model_name = Path(workspace).name
    layers_name = re.sub(r"\D+", "Layers", model_name)
    layers_folder = Path(workspace, layers_name)
    if layers_folder.exists():
        arcpy.AddMessage("Rasters folder: {0} exists".format(layers_name))
    else:
        layers_folder.mkdir(parents=True)
        arcpy.AddMessage("Rasters folder {0} created".format(layers_name))

def fgdb_schema(workspace, schema, dem):
    """Create file geodatabase using XML
    schema and set coordinate system based
    on input DEM if it doesn't already exist"""
    model_name = Path(workspace).name
    fgdb = "{0}.gdb".format(model_name)
    if arcpy.Exists(str(Path(workspace, fgdb))):
        arcpy.AddMessage("{0} file geodatabase exists".format(fgdb))
    else:
        new_fgdb = arcpy.CreateFileGDB_management(str(workspace), fgdb)
        import_type = "SCHEMA_ONLY"
        config_keyword = "DEFAULTS"
        arcpy.AddMessage("New {0} file geodatabase created".format(fgdb))
        arcpy.ImportXMLWorkspaceDocument_management(new_fgdb, schema,
                                                    import_type,
                                                    config_keyword)
        arcpy.AddMessage("ArcHydro schema imported")
        projection = arcpy.Describe(dem).spatialReference
        projection_name = projection.PCSName
        feature_dataset = Path(workspace, fgdb, "Layers")
        arcpy.DefineProjection_management(str(feature_dataset),
                                          projection)
        arcpy.AddMessage("Changed projection to {0}".format(projection_name))

def model_schema(workspace, schema, dem):
    """Create model schema: rasters folder
    and file geodatabase"""
    rasters_directory(workspace)
    fgdb_schema(schema, dem, workspace)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Create a ArcHydro schema')
    parser.add_argument('--workspace', metavar='path', required=True,
                        help='the path to workspace')
    parser.add_argument('--schema', metavar='path', required=True,
                        help='path to schema')
    parser.add_argument('--dem', metavar='path', required=True,
                        help='path to dem')
    args = parser.parse_args()
    model_schema(workspace=args.workspace, schema=args.schema, dem=args.dem)

A: This looks correct to me, and yes if you're looking to use this as a module you would import main. Though, it would probably be better to name it in a more descriptive way.
To clarify how __main__ and the function main() works. When you execute a module it will have a name which is stored in __name__. If you execute the module stand alone as a script it will have the name __main__. If you execute it as part of a module ie import it into another module it will have the name of the module.
The function main() can be named anything you would like, and that wouldn't affect your program. It's commonly named main in small scripts but it's not a particularly good name if it's part of a larger body of code.
In terms letting a user to input arguments when running as a script I would look into either using argparse or click
An example of how argparse would work.
if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description='Create a ArcHydro schema')
    parser.add_argument('--workspace', metavar='path', required=True,
                        help='the path to workspace')
    parser.add_argument('--schema', metavar='path', required=True,
                        help='path to schema')
    parser.add_argument('--dem', metavar='path', required=True,
                        help='path to dem')
    args = parser.parse_args()
    main(workspace=args.workspace, schema=args.schema, dem=args.dem)


text:
Q: Rails 3 - Change HTTP Status to 200 and add status to response body I need to catch the HTTP response just as it's leaving rails and rewrite as follows:

*

*Create a root status node with the status code in it, then

*Rewrite the header status to 200

Eg. For all responses, put their status as a root node and then rewrite their header:
HTTP/1.1 404 Not Found
Content-Type:text/html

This page was not found

Into this:
HTTP/1.1 200 OK
Content-Type: text/html

<status='404'>
This page was not found
</status>

Background:
Using Rails 3 with a Flash client.
Anything other than HTTP 200 cannot be guaranteed to pass through to the client due to limitations of browsers. Some allow 201 through, but not all. Also, any headers will be stripped off most of the time, with only the body getting through.

A: I would use a Rack-Middleware since its really easy to process the header and rewrite the body.
Put this into app/middleware/flashfix.rb
    class FlashFix
      def initialize(app)
        @app = app
      end

      def call(env)
        status, headers, response = @app.call(env)
        if status == 404
          [200, headers, "<status='404'>" + response.body + "</status>"]
        else
          [status, headers, response]
        end
      end
    end

This just checks if Rails returns a response with the status code "404" and then rewrites the the response accordingly.
Then inside an intializer:
     # Loops through all middlewares and requires them
     Dir[File.join(Rails.root,"app/middleware/*.rb")].each do |middleware|
       require middleware
     end

With the middleware in place all you need to do is tell Rails to use it
    class Application < Rails::Application
      config.middleware.use "FlashFix"
    end

If you are unfamiliar with Rack I recommend http://guides.rubyonrails.org/rails_on_rack.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Issue in creating Pagination in Laravel I am trying to use Pagination functionality provided by Laravel. Functionality works correctly for 1st page. However, pagination is not working for subsequent pages.
It is raising an error "Array to String Conversion" while echoing $tableData. Below is my code snippet of view.

  @foreach ($tableData as $d)

    {{$d->ItemMake}}
    {{$d->Item}}
    {{$d->style}}
    {{$d->Price}}
    {{$d->ItemValue}}

 @endforeach

    <?php
        echo $tableData;
     ?>

while using "{{$tableData}}" , its throwing the error,
Error : "htmlentities() expects parameter 1 to be string, array given"
while using "{!! $tableData !!}" , its throwing the error, Error : Array to string conversion

A: The problem is not in pagination.
You can't echo array like string with {!! $tableData !!} or {{ $tableData }} or echo $tableData;
To display contents of an array you should use foreach loop or $tableData[0] to display first element of that array, for example. Also you can use var_dump() or dd() functions if you just want to look what's inside of an array.

A: I think that you want to echo pagination links for next pages.
Change
echo $tableData;

to
{{ $tableData->links }}

and read manual.


text:
Q: Is There Macdeployqt for QT Command Line Executable Binary Without App Bundle? I'm trying to build a command line tool on Mac that doesn't result in .app bundle.
When I run make release, it just gives an executable file since it's a command line tool for terminal.
I understand that macdeployqt lets you package all the necessary files for .app to run without qt installed on another machine.
Is there similar tool for just binary executable?
When I pass the executable to macdeployqt, I get "ERROR: Could not find bundle binary for ...".

A: macdeployqt is run against an existing .app bundle and handles most of the library collection and install_name_tool business to make the bundle deployable.  Even if you were to utilize this tool, you would end up customizing the binary's install_name info manually to suit your purpose.

A: https://github.com/SCG82/macdylibbundler will bundle an app and fix up the install names/rpaths. Disclaimer: I'm the developer.


text:
Q: How To Provide Database Independency in JDBC Without Using Hibernate.? I am trying to solve this problem with the help of properties file, but in a Properties file, we can handle only Database Driver problem. If I want to switch my MySQL to Oracle database I need to change my all query. The problem is how to make query independent in JDBC?
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class DBIndependencyExample {
    public static void main(String[] args) {
        try {
            Properties pros = new Properties();
            InputStream fis = new FileInputStream(
                    "D:\\Programs\\Eclipse\\DBIndependecyByPropertiesFile\\src\\connectdb.properties");
            pros.load(fis);
            String Drivername = pros.getProperty("k1");
            //System.out.println(Drivername);
            String url = pros.getProperty("k2");
            String un = pros.getProperty("k3");
            String pw = pros.getProperty("k4");
            Class.forName(Drivername);
            Connection con = DriverManager.getConnection(url, un, pw);
            System.out.println("Driver Is Loaded With" + Drivername);
            System.out.println("Connection is Opened");
            Statement smt = con.createStatement();
            String sql = pros.getProperty("k5");
            //System.out.println(sql);
            ResultSet rs = smt.executeQuery(sql);
            while (rs.next()) {
                System.out.println("username is:" + rs.getString(1) + " password is:" + rs.getString(2));
            }
            con.close();
            System.out.println("Connection is closed");
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Properties File:
//Mysql Connectivity
//Start Properties File Code
k1=com.mysql.jdbc.Driver
k2=jdbc:mysql://localhost:3306/practice
k3=root
k4=root
k5=select * from student

//Oracle  Connectivity

k1=oracle.jdbc.driver.OracleDriver
k2=jdbc:oracle:thin:@localhost:1521/orcla
k3=scott
k4=manish
k5=select * from dept

A:
If i want to switch my mysql to oracle database i need to change my
  all query.

If your SQL queries rely only on the ANSI SQL and never on proprietary specificites (function, keywords, and...) you should be able to switch from an DBMS to another one without any change in the queries.
Note that Hibernate will not translate for a DBMS specifities to another one as for example translate a query on the DUAL table written in Oracle to a MySQL way.
Hibernate ensures that your SQL queries be portable while you don't create native queries, a possibility still provided by Hibernate.
Here is the original SQL ANSI draft and here a download link for the last version of Information technology -- Database languages -- SQL -- Part 1: Framework (SQL/Framework)

A: I don't think so if you switch to hibernate or any orm frameworks. In case of hibernate you can use hql to write the queries in that way you are database independent no matter what database you switch hibernate will take care. You can even look at Spring CrudRepository. I highly doubtful you can achieve database independent queries just with the JDBC. It is good to begin with JDBC for a long run you should consider orm frameworks.

A: You can write a generic method that can handle any sql query (regardless of the database used). The trick here is to use database metadata to automatically
populate a hash map (a hash map is convenient because we can use the column names as keys) containing the query results. For parameterized queries, you'll need a more complex method, which can be found at the link provided below (DBSelect.getRecordsForCustomQuery). If all your queries targeting different databases are the same, then you don't even have to use metadata, just hardcode the column names.
public Map<String, Object> getQueryResults(String query, Connection conn){

    ResultSet rs=null;
    PreparedStatement stmt=null;
    Map<String, Object> objMap = new HashMap<>();

    stmt = conn.prepareStatement(sqlQuery);
    rs = stmt.executeQuery();
    while(rs.next()){
    for (int i=1;i<=rs.getMetaData().getColumnCount();i++) {
                objMap.put( rs.getMetaData().getColumnName(i), rs.getObject(i));
    }
 }
    return mapObj;

}

You can, of course, modify this method to suit your needs.
A slightly  more elaborate solution which uses reflection and generics can be found here ( https://github.com/IvanGH2/EasyORM ) but you don't
even have to use all of that.


text:
Q: python-telegram-bot: TypeError: can only concatenate str (not "tuple") to str Учусь на Я.Практикуме. Пишем бота, который уведомляет об изменении статуса домашней работы. Код написан, ревьюером проверен, всё хорошо. Но он не запускается. Библиотека python-telegram-bot ругается, выдаёт такую ошибку:
    Traceback (most recent call last):
  File "c:\Dev\homework_bot\homework.py", line 162, in <module>
    main()
  File "c:\Dev\homework_bot\homework.py", line 119, in main
    bot = telegram.Bot(token=TELEGRAM_TOKEN)
  File "C:\Dev\homework_bot\spr7_venv\lib\site-packages\telegram\_bot.py", line 231, in __init__
    self._base_url: str = base_url + self._token
TypeError: can only concatenate str (not "tuple") to str

Я сначала попробовала аннотацией типов присвоить константе TELEGRAM_TOKEN тип str. Вроде поменялся:

Но всё равно выходит та же ошибка. Переустанавливала пакеты, всё без толку.
Заранее спасибо за любую помощь/подсказку!

A: Похоже, что в переменной TELEGRAM_TOKEN у вас хранится не строка, а кортеж. Вам нужно проверить, каким образом вы определяете эту переменную.
Убедитесь, что она правильно задана и не содержит ошибок. В Windows команда для проверки значения переменной окружения:
echo %TELEGRAM_TOKEN%

В Linux и macOS:
echo $TELEGRAM_TOKEN

Также убедитесь, что вы не перезаписываете значение переменной TELEGRAM_TOKEN где-то в коде.
Если после проверки всего вышеуказанного ошибка остается, то попробуйте явно преобразовать значение переменной TELEGRAM_TOKEN к типу str:
bot = telegram.Bot(token=str(TELEGRAM_TOKEN))

Также убедитесь, что вы используете последнюю версию библиотеки python-telegram-bot. Если вы используете устаревшую версию, то могут возникать проблемы совместимости.


text:
Q: how to enable and disable php7 modules in linux server 16.4 I have mad a custom ini files in /etc/php/7.0/mods-available. how can I enable it. I have tried php5enmod, and php7enmod. none worked for me.
Thank you.

A: *

*phpenmod moduleName enables a module to php7 (restart apache after that sudo service apache2 restart)

*phpdismod moduleName disables a module to php7 (restart apache after that sudo service apache2 restart)

*php -m lists the loaded modules

A: If you have several php versions intalled you can also use this syntax:
phpenmod -v 5.6 <modulename>
phpenmod -v 7.1 <modulename>
...

That worked in my case because I have 7.0, 7.1, 7.2 and 7.3 installed, but because of requirements I have to run my apache2 with 7.2.

A: You can simply use the command phpenmod.

A: *

*To check available modules, run php -m - it's a content of /etc/php/yourPHPVersion/mods-available

*Select module from the list and enable it (let's say you want to enable soap) phpenmod soap

*Reload apache2 service apache2 reload or systemctl reload apache2
And you have a module enabled.

*To disable the same module, run phpdismod soap, reload apache2 service apache2 reload


text:
Q: bash rsync script in python works odd I have this problem with bash in python. I want to make script that will make folder based on system date - and this works just fine. The problem is when I want to rsync two directories one with my files to backup and other that is created with system date in name.
    import os
    f = os.system("bash -c 'DATE=folder-`date +%y%m%d;mkdir /home/lol/$DATE;'")
    g = os.system("bash -c 'rsync -av /folderToBackup/ /home/lol/$DATE/;'")

And when rsync copies files they all land in /home/lol/ not in /home/lol/$DATE
please if some one knows the solution, i tried different directories and rsynced files always land not in created folder with date but higher, for example in /home/lol/

A: In the second line, $DATE isn't defined anymore as you start a new shell and it has lost the variable definition of the first call.
Why don't you wrap this into a single shell script or feed the date from Python?  Why are you using Python anyway? Frankly, your approach is nonsensical.
$!/bin/bash
DATE=folder-`date +%y%m%d;mkdir /home/lol/$DATE
rsync -av /folderToBackup/ /home/lol/$DATE/

A: in your example you start a bash and you set the DATE variable so the DATE variable is only available in this bash process. when you start a new bash (for your rsync) you doesn't have set a DATE variable. When you read this variable it is empty. that's why you copy to /home/lol. so for your script just set the DATE variable in the second (rsync) bash process.
i think a better solution for your goal is to use python's datetime and makedirs. then start one os.system bash process for rsync.

A: The issue is the way you handle the variable $DATE.
This variable is visible for the first execution (when you create the directory with the desired date).
When the script tries to execute the rsync, the content of this $DATE variable is unknown to the second execution of os.system().
So you need in some way to communicate this value from the first execution into the second execution.
You can explore the Python module 'subprocess', which is also better than the os module to achieve this kind of results. Here my test:
from subprocess import PIPE
from subprocess import Popen

def exec_and_show(command):
    process = Popen(
        args=command,
        stdout=PIPE,
        shell=True
        )
    return process.communicate()[0]

my_folder = exec_and_show("bash -c 'DATE=folder-`date +%y%m%d`;mkdir /home/lol/$DATE;echo $DATE'")

print "My folder is: {0}".format(my_folder)

And definitely I would not use a programming language for a two-lines execution like this.
Some other answer here which resolves the problem using shell script is better. Not only because the solution is simpler (only TWO lines of code), but also all what is implied in the simplicity (future maintenance, for example).


text:
Q: Fire only one Custom Validator at a time I have two Custom Validators attached to a textbox.  The textbox is to enter comma separated list of emails. The first validator checks that there is not duplicate email address. The second custom validator checks that all the email addresses are in valid format. I have following code and it works fine.
However, when both the failure criteria is met both of them are firing and I get two * at the right side of my textbox. What is the best approach to show only one * at a time?

CODE
<asp:CustomValidator ID="valEmailRecipients" runat="server" ControlToValidate="txtEmailRecipients"
ClientValidationFunction="isUniqueElements" OnServerValidate="IsUniqueEmail_Validate"
Text="*" ErrorMessage="There should be no duplicate email address for a report"
ValidationGroup="Save">
</asp:CustomValidator>

<asp:CustomValidator ID="valEmailFormat" runat="server" ControlToValidate="txtEmailRecipients"
ClientValidationFunction="checkEmailFormat" OnServerValidate="IsValidEmailFormat_Validate"
Text="*" ErrorMessage="Entries should be valid email addresses separated by comma"
ValidationGroup="Save">
</asp:CustomValidator>

REFERENCES:

*

*Validating with a Custom Function for ASP.NET Server Controls

*Enable/Disable asp validation control in javascript

*How to set ValidatorEnable() javascript attribute for a validator?

*Validator enable using Javascript

A: Easiest way:- Have the valEmailRecipients return true if the email is not in a correct format. That is it will do it's function only if other validation was successful.
Other way:-  Disabling and Enabling validators, which can be a pain.
Just out of curiosity, why a problem with 2 asterisks?

A: Create a single Custom Validator, and perform all the validation logic on it.
If one validation didn't pass, set the according error message to it, set the args.IsValid to false and end the method.
On the submit button, remember to check Page.IsValid.


text:
Q: MySql will not import mysql dump mysqldump v 5.10
Dumped entire database into a single .sql file.
Completely removed mysql installation, and reinstalled fresh.
Import Data > dumpedfile.sql
Fails with syntax error every time at same line.
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `AddDate` BEFORE INSERT ON interviewlist FOR EACH ROW
SET NEW.InterviewListDateCreated = CURDATE(); */;;
DELIMITER ;

Always fails when it tries to create the trigger/event/ or procedure. I have multiple triggers defined for most tables. So having to recreate them one by one would be a bit annoying. Did mysqldump put in the wrong syntax?
I am trying to import as root user through MySql Workbench > import data
EDIT: Removing that block of code allowed all of the other triggers to insert properly... odd since the syntax is the exact same on all of them.
Also, redumping the file using "Add Locks/Unlocks" option in mysqldump allows the file to import perfectly. Shrug


text:
Q: Python, Conditionals - Are these equivalent? if config == 'H/2' or 'H' or '2H': pass
if config == 'H/2' or config == 'H' or config == '2H': pass

A: >>> config = 'H/2'
>>> config == 'H/2' or 'H' or '2H'
True
>>> config == 'H/2' or config == 'H' or config == '2H'
True

>>> config = 'H'
>>> config == 'H/2' or 'H' or '2H'
'H'
>>> config == 'H/2' or config == 'H' or config == '2H'
True

>>> config = 'R'
>>> config == 'H/2' or 'H' or '2H'
'H'
>>> config == 'H/2' or config == 'H' or config == '2H'
False

A: Well, since pass does nothing and presumably config.__eq__ has no side-effects, I suppose they're equivalent (in that nothing happens).
If you replace pass with something else, though, you'll notice that the first conditional always executes and the second depends on the value of config.
Perhaps you would like to write
if config in ['H/2', 'H', '2H']:
    # do stuff
    pass

A: Do either:
if config in ('H/2', 'H', '2H'): # more efficient than a list
    do_something()

or (if you are doing this often or the possible set of values is much larger):
# once
config_h_set = set(('H/2', 'H', '2H'))

# later
if config in config_h_set:
    do_something()


text:
Q: Blazor client hosted constructor dependency injection in server controller I am getting an HTTP 500 when performing an API request within a Blazor client-hosted application. The request is successful if I omit the controller parameters, however, once I set a parameter inside the controller I get an HTTP 500.
I have checked and tested the container and the interfaces are registered. The client works as long as I don't supply parameters inside the server controller constructor.
What do I need to do to have contructor injection inside the server controllers within a blazor application?
At the time of writing, I am using Visual Studio 2019 16.2 preview 4 & .NET Core 3 preview.

Startup.cs
public class Startup
{
    private readonly IDependency _dependency;

    public Startup()
    {
        _dependency = new Dependency();
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddNewtonsoftJson();
        services.AddResponseCompression(opts =>
        {
            opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "application/octet-stream" });
        });

        _dependency
            .SetServiceCollection(services)
            .SetServiceProvider(services.BuildServiceProvider());
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseResponseCompression();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBlazorDebugging();
        }

        app.UseClientSideBlazorFiles<Client.Startup>();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
        });

        _dependency
            .SetWebHostEnvironment(env)
            .ConfigureDependencies()
            .ConfigureDatabases();
    }
}

Dependency.cs
public class Dependency : IDependency
{
    private IServiceCollection _services;
    private IServiceProvider _provider;
    private IWebHostEnvironment _environment;

    public IDependency SetServiceCollection(IServiceCollection services)
    {
        if (_services != null)
            throw new AlreadyConfiguredException($"{nameof(services)} is already configured.");

        _services = services;
        return this;
    }

    public IDependency SetServiceProvider(IServiceProvider provider)
    {
        if (_provider != null)
            throw new AlreadyConfiguredException($"{nameof(provider)} is already configured.");

        _provider = provider;
        return this;
    }

    public IDependency SetWebHostEnvironment(IWebHostEnvironment environment)
    {
        if (_environment != null)
            throw new AlreadyConfiguredException($"{nameof(environment)} is already configured.");

        _environment = environment;
        return this;
    }

    public IDependency ConfigureDatabases()
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(_environment.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{_environment.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        var config = builder.Build();
        var database = config.GetConnectionString("MenuDatabase");

        MenuStartup.Configure(_services, database);
        OpeningTimeStartup.Configure(_services, database);

        return this;
    }

    public IDependency ConfigureDependencies()
    {
        // Bounded Contexts

        // Domain Models
        _services.AddTransient<IMenu, Menu.Menu>();

        // Infrastructure
        _services.AddTransient(typeof(IRepository<,>), typeof(Repository<,>));
        _services.AddTransient<IFactory, Factory>();
        _services.AddSingleton<ICompositeCache, MemoryCompositeCache>();
        _services.AddTransient<IDataContextFactory, DataContextFactory>();
        _services.AddTransient<IMenuRepository, MenuRepository>();

        return this;
    }
}

IDependency.cs
public interface IDependency
{
    IDependency SetServiceCollection(IServiceCollection services);
    IDependency SetServiceProvider(IServiceProvider buildServiceProvider);
    IDependency ConfigureDependencies();
    IDependency SetWebHostEnvironment(IWebHostEnvironment environment);
    IDependency ConfigureDatabases();
}

MenuDataController.cs
[Route("api/[controller]")]
public class MenuDataController : Controller
{
    private readonly IMenu _menu;

    public MenuDataController(IMenu menu)
    {
        _menu = menu;
    }

    [HttpGet("[action]")]
    public IEnumerable<SpiceViewModel> Spices()
    {
        return new Spice[] { };
    }
}

Spices.razor
@inject HttpClient Http

    @Title

        Please take our
        brief survey

    and tell us what you think.

    @if (spices == null)
    {

Loading...

    }
    else
    {

            Select list:
            <select class="form-control" id="spicesSelect">
                <option>None</option>
                @foreach (var spice in spices)
                {
                    <option value="@spice.Id">@spice.Name</option>
                }
            </select>

    }

@code {
    [Parameter] string Title { get; set; }

    SpiceViewModel[] spices;

    protected override async Task OnInitAsync()
    {
        spices = await Http.GetJsonAsync<SpiceViewModel[]>("api/MenuData/Spices");
    }
}

A: I upgraded my eyes by wearing my glasses and it turns out there are multiple constructors in the Controller. Turning on server logging as recommended by Microsoft helped quite a lot.

*

*The example I showed microsoft had multiple constructors with a single parameter. The DI does not know which to choose.

*The DI is not activating automatically instance types that are not registered in the container.

A: For people like me who searched "blazor controller dependency injection" and found this question, here's what I got.
The original Blazor client-hosted project template shows you the following code (WeatherForecastController.cs) once you completed the new project creatoin.
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
    this.logger = logger;
}

In order to use the db context that you created on your own (or any other Dependency Injection), you just need to modify the original constructor instead of creating a new one (keep one and only one constructor).
public WeatherForecastController(ILogger<WeatherForecastController> logger, MyDbContext context)
{
    this._context = context;
    this.logger = logger;
}


text:
Q: What is a broken label? Further to my question here, I need to ask why is it bad (as in results and practice) to have :: comment instead of REM within code blocks:
for %%a in (*.pdf) do (
:: This bad, but why?
)

Can someone explain this to me? And thereby restore my faith in batch files!

A: The reason that it's a broken label can be demonstrated by this code:
@ECHO On
SETLOCAL
GOTO fred
ECHO miss this 1
:fred
GOTO :bill
ECHO miss this 2
:bill
GOTO ::charlie
echo miss this 3
::charlie
ECHO all done!
GOTO :EOF

That is, a leading : indicates a label, but the label-name itself may not start :. Now whether :label:with:colons is a valid label, I'll leave to the enthusiastic experimenter. I'd prefer to keep to a simple rule - no colons in label-names.
As for the no-labels-in-code-blocks rule, remember cmd's history. At one time, code-blocks were not allowed. It's a simple-minded processor which may have learned a lot since its inception. It wants to maintain backward-compatibility, so suppose we come across some common constructions within a block:
goto label, goto :label, call label, call :label
this leaves us with a nightmare of possible return-paths and interpretation possibilities. Does goto outofblock terminate the block? Does goto inblock terminate the iteration?
Hence, the simple-minded rule, no labels in blocks. I remember jeb worked out a set of rules where labels can be used, which was interesting. Here's a video


text:
Q: Create and render multiple images on the fly in PHP I am working on the following code. Why am I not able to render generated images to the page on the fly?
<?php
 for ($i = 0; $i <= 3; $i++) {
   $im = imagecreatetruecolor(320, 80);
   $text_color = imagecolorallocate($im, 255, 255, 255);
   imagestring($im, 20, 20, 5,  "Test App", $text_color);

   $img = imagejpeg($im, 'Test.jpg');

   echo '

';

  imagedestroy($im);
  }
?>

What I am getting in the output now is

while the src attributes of the images are 1 !

A: Capture the byte stream, then convert. You'll need to base64_encode the raw byte. Then use it in the image tag:
Basic idea:
for ($i = 0; $i <= 3; $i++) {
    ob_start(); // begin capture
    $im = imagecreatetruecolor(320, 80);
    $text_color = imagecolorallocate($im, 255, 255, 255);
    imagestring($im, 20, 20, 5,  "Test App " . ($i + 1), $text_color);

    $img = imagejpeg($im, null, 100);
    $raw = ob_get_clean(); // get

    echo '

';
}

A: An  tag expects you to supply a filename. Hence you need to save the files and then reference the saved name or your need to embed your image data using something like this:
Embedding Base64 Images

A: imagejpeg() returns a boolean according to its docs here: PHP imagejpeg -- Meaning whether it successfully created the image stream or not.
On the display page you can do something like this:

Create a file called image.php and set this as source:
<?php
  $im = imagecreatetruecolor(320, 80);
  $text_color = imagecolorallocate($im, 255, 255, 255);
  imagestring($im, 20, 20, 5,  "Test App", $text_color);

  header('Content-Type: image/jpeg');

  $img = imagejpeg($im);

  imagedestroy($im);
?>

This will actually treat image.php as an image file. You have to have headers set properly on the output, which your code example won't do. The browser needs to know how to handle data streams.

A: Maybe it would be better to have two separate PHP files:
One which creates the image on-the-fly and returns the data as a JPEG image (say image.php), and another one which renders the HTML code.
Then your HTML would contain something like:

The other option would be to keep using a single PHP file, and convert the binary JPEG image into a base64 string. This is because the "src" attribute either expects a "normal" URL, or base64-encoded image data. See here: https://stackoverflow.com/a/21606233/4555850


text:
Q: Datastage Designer and Sequential File Location Having been thrown into the deep end with DataStage/QualityStage, I'm working on an IBM tutorial on Parallel Jobs and having a hard time getting traction. I think some of the problem is that I'm used to Microsoft conventions. I am even finding the IBM forums difficult to navigate.
The tutorial calls for the import of a CSV file which I have on my workstation, but the properties dialog of the Sequential File stage (which is my data source) seems to map only to directories on the Linux server.
If I need to get a network connection to a shared folder on the Linux server or get a Windows share mounted on the Linux box, I will start that ball rolling, but I'm hoping not as that will be a bit of a bureaucratic nightmare here. How can I import the file from my Windows client? I would be grateful if someone can point me down the right path.

A: Alright
assuming that your datastage SERVER is installed on a linux box ABC.
the easiest way would be to use an FTP tool like winscp (which would give you a nice GUI windows one showing your machine and the other one showing the server)
and from there you can drag and drop the file from your machine to the server folder you like.
Now to do that you would need access to the server on which Datastage is installed.

A: The suggestions from jclozano and Ashish Devassy are both sound, although they require assistance from system administrators to establish permissions for FTP connections. The FTP stage has a lot to recommend it as far as automation.
When I approached my administrators (prior to seeing these suggestions) for help, they just made me an admin on the Linux box so I could solve the problem myself. What I did was create a share on the workstation running the Designer client and then mapped a folder in /mnt to it. I then copied the files to another folder in /home so I could manage the read/write permissions. That was a problem in the /mnt folder, I imagine having something to do with being a Linux to Windows connection.


text:
Q: Android: How can I place a only one list view item at the bottom of the screen? I am trying to implement the DrawerLayout in my sample application.
And I just take the sample NavDrawerLayout code with Image, Title, Count.
The thing is I want to place one item at the bottom of the screen.
Some people say I should use relative layout and layout_alignParentBottom set to true.
But in my MainActivity.java
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);

navDrawerItems = new ArrayList<NavDrawerItem>();

    // adding nav drawer items to array
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
    navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));

mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);

This is my activity_main.xml
<!-- Framelayout to display Fragments -->
<FrameLayout
    android:id="@+id/frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!-- Listview to display slider menu -->
<ListView
    android:id="@+id/list_slidermenu"
    android:layout_width="480dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@color/list_divider"
    android:dividerHeight="1dp"
    android:listSelector="@drawable/list_selector"
    android:background="@color/list_background"/>

Can you please help me?
I am newbie here and any help would be appreciated.


text:
Q: Whenever i suspend when i resume my screen is just black I am running Ubuntu 12.04 on a Sony Vaio machine. System has ran Ubuntu for over 18months and never has this happened before. COnstantly keep update with all updates, however the last half dozen times i have put it into suspend (just shut lid) when i come to wake it up all i have is a totally black screen. No mouse cursor- just blackness!
Can anyone help please? Thanks

A: happens to me to. is said to be becuase you changed power settings from default. For me the black screen goes away when i move the mouse or press a button. Does this work for you too?


text:
Q: Attribute 'id' is not allowed to appear in element 'ns1:customTargeting' I am trying to push multiple creatives with custom targets. It works fine when I push a single creative. But when I try to push more than one creative, DFP throws this error
'Error: Unmarshalling Error:cvc-complex-type.3.2.2Attribute 'id' is not allowed to appear in element 'ns1:customTargeting'.'

Been looking around for any forums related to such errors but without any luck. Please help.

A: This is the forum where DFP API developers answer such questions:
Google's DoubleClick for Publishers API Forum


text:
Q: What's the recommended way to use pg_dump/ysql_dump with YugabyteDB to export data when a table is still receiving inserts? When this workload (SqlSecondaryIndex workload from https://github.com/YugaByte/yb-sample-apps/) is still running
% java -jar yb-sample-apps.jar --workload SqlSecondaryIndex --nodes
127.0.0.1:5433 --num_threads_read 4 --num_threads_write 2

an attempt to use ysql_dump to export the table causes  "Query error: Restart read required" error.
$ ./ysql_dump -h 127.0.0.1 -d postgres --data-only --table sqlsecondaryindex  -f out.txt
ysql_dump: Dumping the contents of table "sqlsecondaryindex" failed: PQgetResult() failed.
ysql_dump: Error message from server: ERROR:  Query error: Restart read required at: { read: { physical: 1592265362684030 } local_limit: { physical: 1592265375906038 } global_limit: <min> in_txn_limit: <max> serial_no: 0 }

But if the same command is executed when the workload is stopped, then ysql_dump command completes successfully without any issues. Is this expected behavior?

A: To read against a consistent snapshot and avoid running into the "read restart" error, pass the --serializable-deferrable option to ysql_dump. For example:
~/tserver/postgres/bin/ysql_dump -h 127.0.0.1 -d postgres \
   --data-only --table sqlsecondaryindex \
   --serializable-deferrable -f data1.csv


text:
Q: Install FFMPEG on Shared Hosting server I have godaddy shared hosting server running under linux. I am trying to install ffmpeg on server but I am unable to install it.
on godaddy, yum is not working.
Anybody have successfully installed FFMPEG on shared hosting? Can you please let me know the steps to install?
Thanks in Advance.

A:
on godaddy, yum is not working.

Of course it's not working, because it's not your server to install packages on.
You may be able to find a statically-linked binary of ffmpeg around, which you should be able to run in a shared hosting environment.
However, if you really need the ability to add/remove packages like this, switch to a VPS solution instead of shared hosting.

A: As ErikA recommends, you will need to find a FFMPEG binary that will run on your particular GoDaddy hosting account.
You will need to upload the binary to your account, preferably in an area outside of the document root.  Be sure to set the permissions on the binary to be executed.
In your application, you will need to set the path to the binary location.  Most applications will be looking for the default location so this will fail.
Here is an older post on this topic.
http://bogdan.org.ua/2007/06/28/compiled-linux-ffmpeg-binary-for-gallery2-download.html

A: You might be able to try this method.
It should be adaptable for each package that can be compiled. You use a docker container with the same distribution GoDaddy is using, compile additional libraries and set the lib path.


text:
Q: Php $_SERVER["REQUEST_METHOD"] alway return get I'm writing some code in my localhost.
index.php:
   $task = null;

    $method = $_SERVER['REQUEST_METHOD'];

    var_dump($method);

    //initialize data
    HttpProtocol::init();

    if (empty($method))
        exitApp("unknown method");

    if ($method == HttpProtocol::get())
        $task = new WebhookVerifyTask();
    else if ($method == HttpProtocol::post())
        $task = new ProcessFacebookEventTask();
    if (is_null($task))
        exitApp("unknown method");

    $task->start();
    http_response_code(200);

it doesn't matter if I send a GET or POST request, the $method will always be GET.
When trying PUT or DELETE - it changes perfectly..
What could cause the $method to always be GET even when POST ?
UPDATE
apparently when i'm sending the request to localhost/path - the above behaviour occur. if i'm sending it to localhost/path/ - the post works perfectly.

A:
apparently when i'm sending the request to localhost/path - the above behaviour occur. if i'm sending it to localhost/path/ - the post works perfectly

Your update also answers your question. if it's /path, but there's no such file, the web server automatically redirects you to /path/ instead. – Janno

when it does this redirection - he does not do it completely with all the request data and methods ?

It cannot. The web server decides to tell the client that it should try another request to a different URL. The web server responds with a 302 Found status code and a Location: http://localhost/path/ header. This causes the client to make another HTTP request to that new location, and that new request will always be a GET request. POST requests cannot be redirected. (Well, theoretically they can be with a 307 Temporary Redirect, but in practice that is not widely supported.)
You need to make your request to the canonical URL directly so as to not cause a redirect.


text:
Q: How to use a dict for resampling a multindex pandas data frame? (>0.18.0) Before pandas 0.18.0 I used to be able to do resample my deeply pivoted table like so:
pivot_df = SoilSensorDf.pivot(status_df, ['A', 'B', 'C'])
resample_methods = map({'A': 'sum',
                        'B': 'mean',
                        'C': 'min'}.get,
                    [x[0] for x in pivot_df.columns])
resample_method_tuple_list = zip(pivot_df.columns, resample_methods)
resample_dict = dict(resample_method_tuple_list)
pivot_df.resample('D', how=resample_dict)

But with pandas 0.18.1, the docs suggest I do it this way
pivot_df.resample('D').agg(resample_dict)

But this gives me the following error which I can't seem to figure out how to resolve. Anyone have any ideas?
File "/.../lib/python2.7/site-packages/pandas/tseries/resample.py", line 293, in aggregate
result, how = self._aggregate(arg, *args, **kwargs)

File "/.../lib/python2.7/site-packages/pandas/core/base.py", line 545, in _aggregate
    result = _agg(arg, _agg_1dim)
  File "/.../lib/python2.7/site-packages/pandas/core/base.py", line 496, in _agg
    result[fname] = func(fname, agg_how)
  File "/.../lib/python2.7/site-packages/pandas/core/base.py", line 475, in _agg_1dim
    colg = self._gotitem(name, ndim=1, subset=subset)
  File "/.../lib/python2.7/site-packages/pandas/tseries/resample.py", line 352, in _gotitem
    return grouped[key]
  File "/.../lib/python2.7/site-packages/pandas/core/base.py", line 330, in __getitem__
    if len(self.obj.columns.intersection(key)) != len(key):
  File "/.../lib/python2.7/site-packages/pandas/indexes/multi.py", line 2031, in intersection
    other, result_names = self._convert_can_do_setop(other)
  File "/.../lib/python2.7/site-packages/pandas/indexes/multi.py", line 2095, in _convert_can_do_setop
    raise TypeError(msg)
TypeError: other must be a MultiIndex or a list of tuples

Example to demonstrate:
df = pd.DataFrame(np.random.randint(0, 100, (10, 3)), columns=list('ABC'),
                  index=pd.date_range('2016-01-01', freq='1400T', periods=10))
df['D'] = ['x', 'x', 'x', 'x', 'x', 'y', 'y', 'y', 'y', 'y']
df.index.name = "timestamp"
df_pivot = pd.pivot_table(df.reset_index(), values=['A', 'B'], index="timestamp",
                          columns=['C', 'D'])
resample_methods = map({'A': 'sum', 'B': 'mean'}.get, [x[0] for x in df_pivot.columns])
resample_method_tuple_list = zip(df_pivot.columns, resample_methods)
resample_dict = dict(resample_method_tuple_list)
df_pivot.resample('D').agg(resample_dict)

A: Looks like this is a bug that will be worked on by the pandas team:
https://github.com/pydata/pandas/issues/13914


text:
Q: What happens to frame when it reaches a switch or router? As I understand it, when one PC sends a frame to another PC through a switch, the frame remains unchanged. The switch receives it and sends the exact same frame. But what happens if we have two PCs connected to a router and we send something between them?

A:
"As I understand it, when one PC sends a frame to another PC through a switch, the frame remains unchanged."

You are correct; switches do not modify the frames they forward in any way.  This is known as transparent bridging as explained in this O'Reilly article titled Basic Switch Operation:

Ethernet switches are designed so that their operations are invisible to the devices on the network, which explains why this approach to linking networks is also called transparent bridging. "Transparent" means that when you connect a switch to an Ethernet system, no changes are made in the Ethernet frames that are bridged.

"But what happens if we have two PCs connected to a router and we send something between them?"

TL;DR
Any packet forwarded by a router will be modified.  Required modifications include a new destination MAC address and a new Frame Check Sequence. But that's only a small part of what happens at the router...

Unlike switches, routers decide what to do with a packet based on its OSI Layer 3 destination address. In this case that is an Internet Protocol (IP) address. Therefore what happens to the packet depends on where the packet is headed. Let's use the image you referred to as an example:

Here we have a router with two interfaces: e1/1/1 (which I'll refer to as E1) and e1/1/2 (which I'll refer to as E2). Notice that the router's two interfaces are in separate subnets, which must always be the case for a router:

*

*E1 is connected to subnetwork 10.0.0.0/24

*E2 is connected to subnetwork 10.0.1.0/24

Now, suppose Computer A (with IP address 10.0.0.2/24 and therefore in subnetwork 10.0.0.0/24) sends a packet to destination IP address 10.0.1.2. Once that packet arrives at the router, the following happens:

*

*Packet arrives on interface E1

*Router determines the destination address is 10.0.1.2

*Router examines its routing table to determine where the packet should go

*The routing table indicates interface E2 is connected to subnetwork 10.0.0.0/24

*The router prepares the packet for transmission on interface E2. This requires modifying the packet in several ways. For example, the new packet will have:

*

*The old destination Layer 2 (MAC) address replaced with a new destination address, which will be the broadcast address FF:FF:FF:FF:FF:FF for the first such packet sent on the interface

*A new Frame Check Sequence (FCS) calculated and added to the packet

*The new packet is transmitted on interface E2

Once the packet is sent to the network segment connected to router interface E2 it is received by Computer B with the IP address 10.0.1.2.
Suppose Computer A sends a packet to the destination IP address 10.0.7.44. Once the packet reaches the router, the following occurs:

*

*Packet arrives on interface E1

*Router determines the destination address is 10.0.7.44

*Router examines its routing table to determine where the packet should go

Now what happens?
Well, if as shown in the graphic, the router truly only has the two interfaces, the router drops the packet because it doesn't have a valid route to the destination network.
In the real world, however, a router is likely to have at least one interface that is configured to be the default route or route of last resort. In the routing table, this is the interface with which network 0.0.0.0/0 is associated. If the router does not have a specific route to a valid network for the packet destined to 10.0.7.44, as its action of "last resort" it will transmit the packet on the interface associated with the default route.
The default route functionality is very important.  Without it the router would be required to have a routing table entry for many (though not all) IP networks on the Internet. Such a table would be very large. Compared to a router with a default route, such a router would require:

*

*More memory to store the routing table

*More CPU time to examine the table (this is done for each incoming packet!)

*Excessive and frequent routing table updates from many other routers on the Internet in order to keep its routing table accurate. Otherwise packets might be forwarded through an interface that in-fact no longer has connectivity to the destination network.

A: Think of a frame as one of those plastic capsules that travel in plastic tubes (some drive-up bank windows used to have those).  A packet is an envelope inside the capsule, and the data is inside the envelope.
A switch is a place where a bunch of different tubes meet.  It will look at the source address and destination address on the capsule, and based on that, send it through the appropriate tube to get where it's going.
Routers care about the envelope, not the capsule.  When a router receives a capsule, it basically opens the capsule and then discards it.  It will then look at the envelope and figure out where it needs to go.  The envelope might need to go to someone's desk.  In that case, it would hand the envelope off to a different delivery system (protocol).  Or it might decide that the envelope needs to go back into the tube system, in which case it would place it into a new capsule and send it on its way.
That is, of course, very simplified, but hopefully it makes the picture a little clearer.

A: A router is basically a switch with additional NAT translation to be able to distinquish between inbound and outbound traffic.
When the internet is involved, and thus NAT is used, port forwarding rules determine what happens with a packet (frame). If its only local, the entire NAT is not used, and thus only the internal switch is used. As such the exact same happens as with a regular switch, the packet remains unchanged.

A: When a data link layer receives the Packet, it encapsulates packet data with
a Header and a Trailer to form the frame.
Frame header contains information such as start frame, addressing, type and control.
Frame trailer contains information such as error detection and stop from.
Scenario #1
Frame traveling in the same LAN:
When PC1 sends a frame to PC2 in the same network, the destination mac address will be the MAC address of PC2 and source mac address will be the mac address of PC1.
In this scenario there will be no change to the frame from source to destination.
Scenario #2
Frame traveling in different LAN:
When PC1 sends a frame to PC2 which is in a different network, the destination mac address will be the mac address of GATEWAY Router not the PC2 mac address. source mac address will be the PC1 mac address. Frame is sent to the Router.
Gateway de-encapsulate the frame to packet and encapsulate it with new frame header and trailer. In this new frame the Packet data is the same and unchanged.
We assume the PC2 is the next hop after the router to receive the frame. In the new frame header the destination mac address will be of PC2 and source mac address will be the mac address of the Router.
In this example the packet data from source to destination had to change its frame header and trailer as it was traveling through different intermediary devices.


text:
Q: How to pass an origin object(NOT COPY) from one activity to another on Android How to pass origin object from one activity to another on Android?
For sure, we can serialized (Serializable, Parcelable, to/from JSON) and pass a copy of the object's data and a new object having the same data could be created; but it will NOT have the same references.
Here is some solution:
Code for the first activity:
final Object objSent = new Object();
final Bundle bundle = new Bundle();
bundle.putBinder(OBJECT_KEY, new ObjectWrapperForBinder(objSent));
startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));

Code for the second activity:
final Object objReceived = ((ObjectWrapperForBinder)getIntent().getExtras().getBinder(OBJECT_KEY)).getData();

but the minimum API Level required 18
Are there other ways?

A: SOLUTION:
BundleCompat allows to use putBinder/getBinder for all Android versions.
ActivityA:
final Bundle bundle = new Bundle();
BundleCompat.putBinder(bundle,KEY, new ObjectWrapperForBinder(callback));
intent.putExtras(bundle);

ActivityB:
object = ((ObjectWrapperForBinder)BundleCompat.getBinder(intent.getExtras(),KEY)).getData();

A: It depends on your goals.
If you're going to work inside one process, you can just simply use Singleton pattern.
But if you want to pass your real object to, for example Service, which has attribute android:isolatedProcess="true" :
<service
    android:name=".service.SomeService"
    android:enabled="true"
    android:exported="false"
    android:isolatedProcess="true"/>

Then you can't pass your origin object to another process.

You can't. Apps in one process cannot hold objects from another
  process, let alone "invoke operations" upon them.

Source: Passing Objects in IPC using Messenger in Android
So, as I can see you are're trying to pass your origin object using Intent mechanism. In my opinion, it's impossible to do it through the Intent's, because Bundle, which contained in Intent doesn't store references to real objects. So, it's impossible.

A: In such case,EventBus will be a great choice.It's something like global Subscribe-Observer and it can help to pass origin object between any objects.
Do this in the activity where you want to pass an object:
EventBus.getDefault().register(this);
EventBus.getDefault().post(new MessageEvent());

Do this in the activity where you want to receive the object:
First,register the activity:
EventBus.getDefault().register(this);

Second,define an method with @Subscriber to receive the object:
@Subscribe
public void onMessageEvent(MessageEvent event)

Hope this will help.

A: Sample object should be Parcelable.
SampleObject objSent=new SampleObject();
Intent intent=new Intent(mContext,NewActivity.class);
intent.putExtra(objSent);
startActivity(intent);


text:
Q: android datepicker animation jerking because of poor performance I have crated an activity with scrollView which holds several buttons and textviews. Before I add the DatePicker into my scrollView, the FPS can keep 60fps. But I don't understand why the FPS drops dramaticly when I added the DatePicker. And I have not find out other widget have such bad performance.
Why I am concerning about the performance of this DatePicker?
Because I want to show this DatePicker in a popup window with popup animation. The animation jerking all the time because of the poor performance of the DatePicker.  I really want improve it. Pease give me some hint about that.
Here is my xml file which I have added the DatePicker.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/common_white"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="test_db" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <Button
                    android:id="@+id/backup_database"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="backup_database" />
                <Button
                    android:id="@+id/restore_database"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="restore_database" />
            </LinearLayout>
        </LinearLayout>
    </ScrollView>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/test_result"
                android:text="hello_world"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <DatePicker
                android:id="@+id/test_picker"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"></DatePicker>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

And here is how I init the DatePicker
    Calendar today = Calendar.getInstance();
    int year = today.get(Calendar.YEAR);
    int month = today.get(Calendar.MONTH) + 1;
    int day = today.get(Calendar.DAY_OF_YEAR);
    DatePicker picker = (DatePicker) findViewById(R.id.test_picker);
    picker.setCalendarViewShown(false);
    picker.updateDate(year, month, day);

GPU rendering profile without DatePicker over 60FPS(I cannot post this picture because of short of reputation)
GPU rendering profile with DatePicker less than 60FPS
GPU rendering profile with DatePicker less than 60FPS
Hierarchy View analysis with DatePicker, measure more than 1ms, draw more than 15 ms, and of course it cannot reach 60FPS.
Hierarchy View analysis with DatePicker
And I think my phone is not that slow, as it could easily got 60 FPS when running the Palette example from support v7 example which holds many textviews and imageviews. Here is the screenshot.(I cannot post this picture because of short of reputation)

A: Here comes the solution by myself
It is the fading edge effect that slow down the performance of the date picker. Detail information please refer to
Why are fading edges slow?
and
http://www.curious-creature.com/2008/12/22/why-is-my-list-black-an-android-optimization/
For using date picker with good performance, simply disable the fading edge effect would work.
android:fadingEdge="none"

For other widget which enable the fading edge effect, it will slow down the draw process.
How to make own custom fading edge effect?
Draw a fading edge drawable at your own view like this:
private final PaintDrawable mGradientDrawable;
private final ShapeDrawable.ShaderFactory mShaderFactory;

mShaderFactory = new ShapeDrawable.ShaderFactory() {
    @Override
    public Shader resize(int width, int height) {
        LinearGradient lg = new LinearGradient(0, 0, 0, height,
                new int[]{
                        0xffffffff,
                        0x00ffffff,
                        0x00ffffff,
                        0xffffffff,},
                new float[]{0, 0.3f, 0.5f, 1},
                Shader.TileMode.REPEAT);
        return lg;
    }
};
mGradientDrawable = new PaintDrawable();
mGradientDrawable.setShape(new RectShape());
mGradientDrawable.setShaderFactory(mShaderFactory);

The drawable will create a gradient from color white to transparent.


text:
Q: Python is passing 32bit pointer address to C functions I would like to call my C functions within a shared library from Python scripts. Problem arrises when passing pointers, the 64bit addresses seem to be truncated to 32bit addresses within the called function. Both Python and my library are 64bit.
The example codes below demonstrate the problem. The Python script prints the address of the data being passed to the C function. Then, the address received is printed from within the called C function. Additionally, the C function proves that it is 64bit by printing the size and address of locally creating memory. If the pointer is used in any other way, the result is a segfault.
CMakeLists.txt
cmake_minimum_required (VERSION 2.6)
add_library(plate MODULE plate.c)

plate.c
#include <stdio.h>
#include <stdlib.h>

void plate(float *in, float *out, int cnt)
{
    void *ptr = malloc(1024);
    fprintf(stderr, "passed address: %p\n", in);
    fprintf(stderr, "local pointer size: %lu\n local pointer address: %p\n", sizeof(void *), ptr);
    free(ptr);
}

test_plate.py
import numpy
import scipy
import ctypes

N = 3
x = numpy.ones(N, dtype=numpy.float32)
y = numpy.ones(N, dtype=numpy.float32)
plate = ctypes.cdll.LoadLibrary('libplate.so')

print 'passing address: %0x' % x.ctypes.data
plate.plate(x.ctypes.data, y.ctypes.data, ctypes.c_int(N))

Output from python-2.7

In [1]: run ../test_plate.py
passing address: 7f9a09b02320
passed address: 0x9b02320
local pointer size: 8
local pointer address: 0x7f9a0949a400

A: The problem is that the ctypes module doesn't check the function signature of the function you're trying to call. Instead, it bases the C types on the Python types, so the line...
plate.plate(x.ctypes.data, y.ctypes.data, ctypes.c_int(N))

...is passing the the first two params as integers. See eryksun's answer for the reason why they're being truncated to 32 bits.
To avoid the truncation, you'll need to tell ctypes that those params are actually pointers with something like...
plate.plate(ctypes.c_void_p(x.ctypes.data),
            ctypes.c_void_p(y.ctypes.data),
            ctypes.c_int(N))

...although what they're actually pointers to is another matter - they may not be pointers to float as your C code assumes.

Update
eryksun has since posted a much more complete answer for the numpy-specific example in this question, but I'll leave this here, since it might be useful in the general case of pointer truncation for programmers using something other than numpy.

A: Python's PyIntObject uses a C long internally, which is 64-bit on most 64-bit platforms (excluding 64-bit Windows). However, ctypes assigns the converted result to pa->value.i, where value is a union and the i field is a 32-bit int. For the details, see ConvParam in Modules/_ctypes/callproc.c, lines 588-607 and 645-664. ctypes was developed on Windows, where a long is always 32-bit, but I don't know why this hasn't been changed to use the long field instead, i.e. pa->value.l. Probably, it's just more convenient most of the time to default to creating a C int instead of using the full range of the long.
Anyway, this means you can't simply pass a Python int to create a 64-bit pointer. You have to explicitly create a ctypes pointer. You have a number of options for this. If you're not concerned about type safety, the simplest option for a NumPy array is to use its ctypes attribute. This defines the hook _as_parameter_ that lets Python objects set how they're converted in ctypes function calls (see lines 707-719 in the previous link). In this case it creates a void *. For example, you'd call plate like this:
plate.plate(x.ctypes, y.ctypes, N)

However, this doesn't offer any type safety to prevent the function from being called with an array of the wrong type, which will result in either nonsense, bugs, or a segmentation fault. np.ctypeslib.ndpointer solves this problem. This creates a custom type that you can use in setting the argtypes and restype of a ctypes function pointer. This type can verify the array's data type, number of dimensions, shape, and flags. For example:
import numpy as np
import ctypes

c_npfloat32_1 = np.ctypeslib.ndpointer(
    dtype=np.float32,
    ndim=1,
    flags=['C', 'W'])

plate = ctypes.CDLL('libplate.so')

plate.plate.argtypes = [
    c_npfloat32_1,
    c_npfloat32_1,
    ctypes.c_int,
]

N = 3
x = np.ones(N, dtype=np.float32)
y = np.ones(N, dtype=np.float32)

plate.plate(x, y, N)  # the parameter is the array itself

A: If you don't tell ctypes what type the parameters are, it attempts to infer it from the values that you pass to the function. And this inference will not always work as you need.
The recommended way to deal with this is to set the argtypes attribute of the function and so explicitly tell ctypes what the parameter types are.
plate.plate.argtypes = [
    ctypes.POINTER(ctypes.c_float),
    ctypes.POINTER(ctypes.c_float),
    ctypes.c_int
]

Then you can call the function like this:
plate.plate(x.ctypes.data, y.ctypes.data, N)

A: Actually, You should set plate.argstype = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_int], and then it will be ok to accept the address in c func from python.
I met the problem and I solved it as what I say.


text:
Q: Accessing SearchDescriptor properties for testing I am separating my query building and query execution, so I have a QueryBuilder which returns a SearchDescriptor<Video>
So to put it into context in my Web Api Controller:
SearchDescriptor<ElasticVideo> documentQuery = _queryBuilder.BuildDocumentQuery(elasticSearchParameters);
ISearchResponse<ElasticVideo> documentResults = _videoRepository.Search(documentQuery);

But when it comes to testing the QueryBuilder I can't access any of the properties on the SearchDescriptor returned in order to validate my test, for example:
        [Test]
        public void BuildDocumentQuery_WithEmptyPhrase_ReturnsProperlyFormedQueryDescriptor()
        {
            var elasticSearchVideoQueryBuilder = new ElasticSearchVideoQueryBuilder();
            var descriptor = elasticSearchVideoQueryBuilder.BuildDocumentQuery(new ElasticSearchVideoParameters());
            descriptor.// How can I get the raw query?
        }

I can see in the source code that there doesn't appear to be anything to expose this? Does anyone else have a similar problem?

A: I don't know exactly how do you build your query, but you can cast SearchDescriptor to ISearchRequest to get more details.
var searchDescriptor = new SearchDescriptor<ElasticsearchProject>()
    .From(0)
    .Size(20)
    .Query(q => q.Match(m => m.OnField(f => f.Country).Query("Country")));

var query = ((ISearchRequest) searchDescriptor).Query.Match.Query;

Assert.AreEqual("Country", query);

A: Okay, I found a way around this, but it means I will have to parse the JSON string back into an object
        var elasticSearchVideoQueryBuilder = new ElasticSearchVideoQueryBuilder();
        var descriptor = elasticSearchVideoQueryBuilder.BuildDocumentQuery(new ElasticSearchVideoParameters());

        var settings = new ConnectionSettings(new Uri("http://localhost:123"));
        var client = new ElasticClient(settings);

        var jsonString = Encoding.UTF8.GetString(client.Serializer.Serialize(descriptor));


text:
Q: Javascript not always loading I have a simple home page slider that I am trying to get up. I have tried it with flexslider and a few other slider javascript scripts.  What's weird is that it loads just great on the first page load and if I do a hard refresh it.  In both instances it loads as you would expect.  However, if you click away from the page with the slider and then back to the page (without doing a hard refresh), the slider doesn't show up at all.
I'm on a new rails 4.0.0 app.
I have placed the flexslider and other slider jquery code in the vender/assets/javascript directory.  Then in the app/assets/javascript/pages.js.coffee page I have:
$(document).ready ->
  $(".flexslider").flexslider animation: "slide"

I've also changed it around to:
$(window).load ->
  $(".flexslider").flexslider animation: "slide"

as well as:
$ ->
  $(".flexslider").flexslider animation: "slide"

but all result in the same problem.
Any idea what I might be missing?

A: I think the problem is because you have turbolinks gem, which only loads part or page, not all of it. So document.ready event does not work. You could try this:
$(window).bind 'page:change', ->
  $(".flexslider").flexslider animation: "slide"


text:
Q: Feynman diagram, which virtual particle? Hi I have been asked to produce the lowest order Feynman diagram for the following scattering process:
$$a.~~~ \mu^-+\mu^-\rightarrow \mu^-+\mu^-$$
$$b.~~~ \mu^-+\mu^+\rightarrow \mu^-+\mu^+$$
The Muon can interact via the electromagnetic and weak forces (and gravity). So how do I know whether the virtual particle in each elastic scattering process is a photon or Z boson? My first guess would be the photon, but I'm unsure why.

A: You have no way to know if the virtual particle is a gamma or a Z. Actually, it does not really make sense, since no measurement can tell you what has been exchanged. You always have to envisage all the possibilities resulting from the perturbative series used to describe the theory. It's a bit as asking in the double slits young experiment, which slit has been chosen by the particle before reaching the screen.
However when the energy $\sqrt{s}$ in the center of mass of the ($\mu^+$, $\mu^-$) is close to the mass of the Z, you can assume that only the Z exchange matters (because of the propagator shape). On the contrary, when $\sqrt{s}$ is close to 0, the Z exchange can be neglected, the photon dominates.

A: The amplitude for low-energy muon scattering mediated by $Z$ bosons is given the the muon's "weak charge," in the same way that the amplitude for scattering mediated by photons is given by the electric charge.  In units where the weak charge of the neutrino is 1, the weak charge of the charged leptons is suppressed; I think at first order it's $1-\frac14\sin^2\theta_W$, with $\theta_W$ the weak mixing angle.  Interference between the EM exchange and the weak exchange will introduce a parity-violating term into the low-energy scattering.  This "weak charge" has been measured for the proton and electron (which show the same suppression), but those experiments (with stable particles) are quite challenging and I'm not aware of an effort to make the same measurements for the muon.  The canonical review article on the subject is here.
As Paganini says, if the momentum transfer in the scattering reaction is close the $Z$ mass, that interaction dominates.


text:
Q: EF Core 2.0 ThenInclude() navigation not reachable I'm trying to fetch entities which have children and grandchildren
The Entities are following code first conventions and are as follows
//This is the father class
public partial Class Solicitud{
    [InverseProperty("Solicitud")]
    public virtual ICollection<Operacion> Operaciones { get; set; }
    //Other properties
}

//This is the child class
public partial Class Operacion{
    [JsonIgnore] //This is so when serializing we don't get a circular reference
    [InverseProperty("Operaciones")]
    public virtual Solicitud Solicitud { get; set; }
    public virtual Practica Practica { get; set; }
    //Other Properties
}

//This is the grandchild class
public partial Class Practica
{
    String Nombre;
    //Other Properties
}

If I do
context.Solicitudes
            .Include(w => w.Operaciones)
            .Where(x => x.Profesional == profesional).OrderBy(something);

It works out ok, populating the "Operaciones" collections, and leaving the "Practica" property as null as expected.
The problem arises when I try to get the grandchildren, by use of
context.Solicitudes
            .Include(w => w.Operaciones)
                .ThenInclude(o => o.Practica)
            .Where(x => x.Profesional == profesional);

There, it still populates Operaciones, but in each Operacion the property practica stays null, and I get the following message
    warn: Microsoft.EntityFrameworkCore.Query[100106]
  The Include operation for navigation '[w].Operaciones.Practica' is unnecessary and was ignored because the navigation is not reachable in the final query results. See https://go.microsoft.com/fwlink/?linkid=850303 for more information.

Which to me makes no sense because I could very well do
String something = solicitud.Operaciones.ElementAt(0).Practica.Nombre;

Is this a bug? Is there any way I can avoid using nested selects? The classes are really big in that they have a lot of Properties and it becomes difficult to mantain changes to the domain model using that approach.
Thanks.
Edit: edited title.

A: It seems that you need to start the query from the entity you want as a result. In your example Practica is not present in the result of your query because is nested (there is no direct path between your resulting query and Practica).
You could try to rewrite your query this way (and add a navigation property inside Practica if not already present):
context.Practicas
    .Include(p => p.Operacion)
    .ThenInclude(o => o.Solicitud)
    .Where(p => p.Operacion.Solicitud.Profesional == profesional)
    .ToList();

A: Well, I think this is actually a bug.
This database is running in SQL Server 2016 and migrated from an old, kind of unmaintained Visual Fox Pro database via an Integration Services package.
Somehow something went wrong while writing said package and the database ended up with rows that broke a foreign key restriction (specifically the one relating Operaciones to Practicas), once I deleted the rows that broke the restriction I ran the query again and it successfully populated every member it was supposed to.
I think this is a bug because the warning message was, in my opinion, a bit misleading. It said that I couldn't access Practica from Solicitud which is tecnically true because it could never get me any Practica as the database was broken, but not very accurate in why I couldn't get them.


text:
Q: Return rows with last appearance of an id I have a log table of entries in the following format:
timestamp,id,enabled
2014-11-07 17:16:38,1,TRUE
2014-11-07 17:44:30,2,TRUE
2014-11-07 18:07:13,2,FALSE
2014-11-07 18:11:48,1,TRUE

I want to return the last row where each particular id appears. So in the case above, the output would be:
2014-11-07 18:07:13,2,FALSE
2014-11-07 18:11:48,1,TRUE

How can I do that in R?

A: There are a number of ways to do this. Here's a method using the dplyr package, assuming your data frame is called dat:
library(dplyr)

dat %>% group_by(id) %>%
  slice(length(id))  # This selects the last row for a given ID

                 date id enabled
1 2014-11-07 18:11:48  1    TRUE
2 2014-11-07 18:07:13  2   FALSE

If you want to select the last row based on some ordering variable, like date in this case, then order by date first before slicing:
# First, convert date string to date format
library(lubridate)
dat$date = ymd_hms(dat$date)

dat %>% group_by(id) %>%
  arrange(date) %>%
  slice(length(id))

UPDATE: Or, if you're ever code-golfing with @BenBolker and need to shave a  few characters off your score:
dat %>% group_by(id) %>%
  slice(n())

A: Just couple of solutions without loading any packages
x <- read.csv(textConnection("timestamp,id,enabled
2014-11-07 17:16:38,1,TRUE
2014-11-07 17:44:30,2,TRUE
2014-11-07 18:07:13,2,FALSE
2014-11-07 18:11:48,1,TRUE"),header = TRUE,stringsAsFactors =FALSE)

# Solution 1
aggregate(x,by=list(x$id),FUN=function(x){tail(x,1)})

# Solution 2
data.frame(do.call('rbind',as.list(by(x,x$id,tail,1))),
                      stringsAsFactors = FALSE)

A: The solution in plyr is particularly compact (although probably slower than dplyr):
library("plyr")
ddply(dat,"id",tail,1)


text:
Q: Return string that contain 2 words in Python I want to search for specific words in one string in my dataset. I already know how to search for these words separately, but now I only want to search for strings that contain both words.
This is my script when I search for separate words, for example 'hello' and 'goodbye'. This also returns strings with only the word 'hello' in it:
df_return=df[df['openfield'].str.contains("hello|bye")==True]

How can I change this script in order to return only the strings that contains both the words somewhere in this string? And not the strings that only contain one of the two words?

A: Maybe this works:
df_return=df[(df['openfield'].str.contains("hello")) & (df['openfield'].str.contains("bye"))]


text:
Q: Issue with "org.eclipse.jdt.launching.IVMInstall.getLibraryLocations()" When I try to run my Java program in Eclipse I get the following error:
"An internal error occurred during: "Launching ConvertExcelToJSON".
Cannot invoke "org.eclipse.jdt.launching.IVMInstall.getLibraryLocations()" because "install" is null"
I have never seen the error before, the program has run with no problem before. Yesterday I got updates to my work machine and maybe that caused something to give me this error.
Anyone seen this before and perhaps have a solution to it?

A: In my case, there was a difference in project's execution environment and installed JDK.
I changed it from Right Click on Project -> Build Path -> Configure Build Path -> Libraries -> JRE System Libraries -> Select same version as installed JDK and it worked.

A: It happened after I changed my Installed JREs configuration. Eclipse's default bundled JRE 16 was selected, but my project was set to Java 8 everywhere in project configurations.
Following fixed my case:
Go to Run > Run Configurations then go to JRE tab and update the project JRE according to new configuration. So that JRE version in eclipse matches the project requirements.


text:
Q: How to write selected columns to Kafka topic? I am using spark-sql-2.4.1v with java 1.8.
and kafka versions spark-sql-kafka-0-10_2.11_2.4.3 and kafka-clients_0.10.0.0
StreamingQuery queryComapanyRecords =
                 comapanyRecords
                 .writeStream()
                .format("kafka")
                .option("kafka.bootstrap.servers",KAFKA_BROKER)
                .option("topic", "in_topic")
                .option("auto.create.topics.enable", "false")
                .option("key.serializer","org.apache.kafka.common.serialization.StringDeserializer")
                .option("value.serializer", "com.spgmi.ca.prescore.serde.MessageRecordSerDe")
                .option("checkpointLocation", "/app/chkpnt/" )
                .outputMode("append")
                .start();

queryLinkingMessageRecords.awaitTermination();

Giving error :
Caused by: org.apache.spark.sql.AnalysisException: Required attribute 'value' not found;
    at org.apache.spark.sql.kafka010.KafkaWriter$$anonfun$6.apply(KafkaWriter.scala:71)
    at org.apache.spark.sql.kafka010.KafkaWriter$$anonfun$6.apply(KafkaWriter.scala:71)
    at scala.Option.getOrElse(Option.scala:121)

I tried to fix as below, but unable to send the value i.e. which is a java bean in my case.
  StreamingQuery queryComapanyRecords =
                     comapanyRecords.selectExpr("CAST(company_id AS STRING) AS key", "to_json(struct(\"company_id\",\"fiscal_year\",\"fiscal_quarter\")) AS value")
                    .writeStream()
                    .format("kafka")
                    .option("kafka.bootstrap.servers",KAFKA_BROKER)
                    .option("topic", "in_topic")
                    .start();

So is there anyway in java how to handle/send this value( i.e. Java
  bean as record) ??.

A: Kafka data source requires a specific schema for reading (loading) and writing (saving) datasets.
Quoting the official documentation (highlighting the most important field / column):

Each row in the source has the following schema:
...
value binary
...

In other words, you have Kafka records in the value column when reading from a Kafka topic and you have to make your data to save to a Kafka topic available in the value column as well.
In other words, whatever is or is going to be in Kafka is in the value column. The value column is where you "store" business records (the data).
On to your question:

How to write selected columns to Kafka topic?

You should "pack" the selected columns together so they can all together be part of the value column. to_json standard function is a good fit so the selected columns are going to be a JSON message.
Example
Let me give you an example.
Don't forget to start a Spark application or spark-shell with the Kafka data source. Mind the versions of Scala (2.11 or 2.12) and Spark (e.g. 2.4.4).
spark-shell --packages org.apache.spark:spark-sql-kafka-0-10_2.11:2.4.4

Let's start by creating a sample dataset. Any multiple-field dataset would work.
val ns = Seq((0, "zero")).toDF("id", "name")
scala> ns.show
+---+----+
| id|name|
+---+----+
|  0|zero|
+---+----+

If we tried to write the dataset to a Kafka topic, it would error out due to value column missing. That's what you faced initially.
scala> ns.write.format("kafka").option("topic", "in_topic").save
org.apache.spark.sql.AnalysisException: Required attribute 'value' not found;
  at org.apache.spark.sql.kafka010.KafkaWriter$.$anonfun$validateQuery$6(KafkaWriter.scala:71)
  at scala.Option.getOrElse(Option.scala:138)
  ...

You have to come up with a way to "pack" multiple fields (columns) together and make it available as value column. struct and to_json standard functions will do it.
val vs = ns.withColumn("value", to_json(struct("id", "name")))
scala> vs.show(truncate = false)
+---+----+----------------------+
|id |name|value                 |
+---+----+----------------------+
|0  |zero|{"id":0,"name":"zero"}|
+---+----+----------------------+

Saving to a Kafka topic should now be a breeze.
vs.write.format("kafka").option("topic", "in_topic").save


text:
Q: How to trace DbQuery parameter values We are tracing the generated SQL using qry.ToString.
How can we trace the parameter values too.
DbQuery (in contrast to ObjectQuery) does not have a Parameters property.
Using SqlProfiler is not an option. We are tracing using log4net in production.

A: For a workaround using reflection see Access to DbQuery parameters for logging.
I made a feature request at CodePlex


text:
Q: prebuild-install warn install No prebuilt binaries found (target=3 runtime=napi arch=arm libc= platform=linux) I am a new-b at this hole R-pi thing and linux
it seems like the problem is that I have a 64bit processor and the code is build for 32.
is there a way to fix this?
lw.comm-server $ npm install node-hid

> node-hid@2.1.2 install /home/----/lw.comm-server/node_modules/node-hid
> prebuild-install --runtime napi || node-gyp rebuild

prebuild-install warn install No prebuilt binaries found (target=3 runtime=napi arch=arm libc= platform=linux)
Package libusb-1.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libusb-1.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libusb-1.0' found
gyp: Call to 'pkg-config libusb-1.0 --cflags-only-I | sed s/-I//g' returned exit status 0 while in binding.gyp. while trying to load binding.gyp
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:351:16)
gyp ERR! stack     at ChildProcess.emit (events.js:314:20)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:276:12)
gyp ERR! System Linux 5.15.61-v7l+
gyp ERR! command "/usr/bin/node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /home/----/lw.comm-server/node_modules/node-hid
gyp ERR! node -v v12.22.12
gyp ERR! node-gyp -v v5.1.0
gyp ERR! not ok
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! node-hid@2.1.2 install: `prebuild-install --runtime napi || node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the node-hid@2.1.2 install script.

I am trying to install laserweb on the pi.
thanks for your help
Danny


text:
Q: using drupal and bootstrap subtheme - jquery not working I have the bootstrap theme (using a subtheme) and have included my own scripts.js file (from my .info) when I enter code such as alert("hello"); then it works fine. But nothing happens when I try $('#edit-profile-teacher').hide();
There are no errors in the console and I have no idea why something so basic is not working.
I am using jquery update module and have it set to 1.7
Cheers,
Garry.

A: You should provide all JS code by extending the Drupal behaviors; like so:
(function ($) {
  Drupal.behaviors.MyCustomTheme = {
    attach: function (context, settings) {

      // Do anything you want here.
      $('#some-selector').hide();

    }
  };
})(jQuery);

While other approaches will work (e.g. just adding on document load), this is the proper way of adding JS in Drupal themes.

A: I had to wrap jquery in this for it to work in drupal.
(function($){
$(document).ready(function(){
    //your stuff here
    alert('what up?!');
    $('#edit-profile-teacher').hide();
});
}(jQuery));


text:
Q: Typescript: Import value from object Lets say I have a typescript file environment.ts where I export
export const environment = {
    host: localhost:8080,

    // more keys/values
}

Lets say I have another file url.ts where I want to import the environment object.
import { environment } from 'environments/environment';

Which works fine. I could do there something like
const host = environment.host

Question:
But, is there any way to just import the host value directly?

A: Instead of exporting a toplevel object named environment you could export each value separately
export const host = 'localhost:8080';
export const foo = 'bar';

and then import them like this
import { host, foo } from 'environments/environment'

or import them all like this
import * as environment from 'environments/environment'

A: if you are working with angular cli, you could modify your .angular-cli.json file like this:

{
  "defaults": {
    "serve": {
      "port": 8080,
      "host": "yourHost"
    }
  }
}


text:
Q: In python, If I perform an fft on complex data, then irfft only the positive frequencies, how does that affect the data? So I am trying to perform a frequency shift on a set of real valued points.  In order to achieve a frequency shift, one has to multiply the data by a complex exponential, making the resulting data complex. If I multiply by just a cosine I get results at both the sum and difference frequencies. I want just the sum or the difference.
What I have done is multiply the data by a complex exponential, use fft.fft() to compute the fft, then used fft.irfft() on only the positive frequencies to obtain a real valued dataset that has only a sum or difference shift in frequency. This seems to work great, but I want to know if there are any cons to doing this, or maybe a more appropriate way of accomplishing the same goal. Thanks in advance for any help you can provide!

A: What you are doing is perfectly fine.  You are generating the analytic signal to accommodate the negative frequencies in the same way a discrete Hilbert transform would.  You will have some scaling issues - you need to double all the non-DC and non-Nyquist signals in the real frequency portion of the FFT results.
Some practical concerns are that this method imparts a delay of the window size, so if you are trying to do this in real-time you should probably examine using a FIR Hilbert transformer and the appropriate sums.  The delay will be the group delay of the Hilbert transformer in that case.
Another item of concern is that you need to remember that the DC component of your signal will also shift along with all the other frequencies.  As such I would recommend that you demean the data (save the value) before shifting, zero out the DC bin after you FFT the data (to remove whatever frequency component ended up in the DC bin), then add the mean back to preserve the signal levels at the end.


text:
Q: TextInputLayout inside of a scroll view label not announced I have a not so complex layout, that is using a  component, inside of a scroll view that has a nested LinearLayout, the problem is that Talkback doesn't announces the label.
 <?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin">

    <LinearLayout
        android:id="@+id/content_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginLeft="@dimen/margin2x"
        android:layout_marginRight="@dimen/margin2x"
        android:animateLayoutChanges="true"
        android:contentDescription="Some Form Description"
        android:orientation="vertical">

        <TextView
            android:id="@+id/some_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/margin"
            android:focusable="true"
            android:text="some field text" />

        <android.support.design.widget.TextInputLayout
            android:id="@+id/some_field_in_form_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/editText1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentStart="true"
                android:hint="Label for field" />

        </android.support.design.widget.TextInputLayout>

    </LinearLayout>

</ScrollView>

Talkback navigation skips the label, if the field has a value the user is not going to know what's the purpose of that field.

A: After some investigation I found the issue is because the LinearLayout has a content Description, is going to capture all the events. In my case I need to announce it, in order to fix my issue I had to explicitly set the children to be focusable.
   <android.support.design.widget.TextInputLayout
        android:id="@+id/some_field_in_form_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:focusable="true">

If the LinearLayout is the only parent this doesn't happen.


text:
Q: django.db.utils.DatabaseError: ORA-30673: column to be modified is not an identity column thanks everybody,
I have a django project, this is my enviroment:
Database:
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production
Python:
Python 3.5.1rc1
cx-Oracle==6.3
Django==2.0.4
I am trying this:
 python manage.py test

I am getting this error:
django.db.utils.DatabaseError: ORA-30673: column to be modified is not an identity column

Thanks.

A: It appears that you are trying to set a column to be the identity column, using the ALTER TABLE command. Oracle, however, tells you that you can't do that.
An example:
Create a table:
create table test (id number);

This command raises the ORA-30673:
alter table test modify id number generated by default on null as identity;

You should create a new identity column:
alter table test add id_new number generated by default on null as identity;

Then copy data into a new column, if necessary:
update test set id_new = id;

Drop the old ID column:
alter table test drop column id;

Rename the new column to the old name:
alter table test rename column id_new to id;

Expect problems if the old ID column was a primary key, used in enforcing foreign key constraint(s).