text:
Q: Get point in 3D space aligned to camera view I am trying to use Frustum to detect whether or not an object is within a square part of the screen (see image below) It's a UI image working as the aimbox not a 3D object.
The original post is here: Detect if an object in 3D space is within/touches a UI image's bounds
Right now I can get the Frustum and drawing the box to work, but only looking in one direction.
I need to be able to calculate new points when the camera turns and I can't figure out how.
The code below kinda works, but I need to offset the positions so they align with the view when the camera is moving.
Edit: Right now nothing is supposed to happen but drawing the box and get that to work. Collision detection comes after.
// Draw aimbox
Vector3 camPosOffset = camPos + cam.transform.forward * maxDistance;

float frustumHeight = (2.0f * maxDistance * Mathf.Tan(cam.fieldOfView * 0.5f * Mathf.Deg2Rad));

cubeVerts[0] = new Vector3(camPos.x, camPos.y, camPos.z);
cubeVerts[1] = new Vector3(camPos.x, camPos.y, camPos.z);
cubeVerts[2] = new Vector3(camPos.x, camPos.y, camPos.z);
cubeVerts[3] = new Vector3(camPos.x, camPos.y, camPos.z);
cubeVerts[4] = new Vector3(camPosOffset.x - frustumHeight, camPosOffset.y + frustumHeight, camPosOffset.z);
cubeVerts[5] = new Vector3(camPosOffset.x + frustumHeight, camPosOffset.y + frustumHeight, camPosOffset.z);
cubeVerts[6] = new Vector3(camPosOffset.x - frustumHeight, camPosOffset.y - frustumHeight, camPosOffset.z);
cubeVerts[7] = new Vector3(camPosOffset.x + frustumHeight, camPosOffset.y - frustumHeight, camPosOffset.z);

for (int i = 0; i < edges.Length; i += 2)
{
    Debug.DrawLine(cubeVerts[edges[i]], cubeVerts[edges[i + 1]], Color.red);
}

https://imgur.com/iXQlE04

A: Simplest version: Make the aimbox a child of the camera.
Alternative Solution, use camPosOffset also for the first 4 verts like this:
cubeVerts[0] = new Vector3(camPosOffset.x - frustumHeight, camPosOffset.y + frustumHeight, camPosOffset.z);
cubeVerts[1] = new Vector3(camPosOffset.x + frustumHeight, camPosOffset.y + frustumHeight, camPosOffset.z);
cubeVerts[2] = new Vector3(camPosOffset.x - frustumHeight, camPosOffset.y - frustumHeight, camPosOffset.z);
cubeVerts[3] = new Vector3(camPosOffset.x + frustumHeight, camPosOffset.y - frustumHeight, camPosOffset.z);
cubeVerts[4] = new Vector3(camPosOffset.x - frustumHeight, camPosOffset.y + frustumHeight, camPosOffset.z) + cam.forward * 3;
cubeVerts[5] = new Vector3(camPosOffset.x + frustumHeight, camPosOffset.y + frustumHeight, camPosOffset.z) + cam.forward * 3;
cubeVerts[6] = new Vector3(camPosOffset.x - frustumHeight, camPosOffset.y - frustumHeight, camPosOffset.z) + cam.forward * 3;
cubeVerts[7] = new Vector3(camPosOffset.x + frustumHeight, camPosOffset.y - frustumHeight, camPosOffset.z) + cam.forward * 3;

A: After fiddling for almost two days I got exactly what I wanted.
        //Draw aimbox

    float frustumHeight = ((2.0f * maxDistance * Mathf.Tan(cam.fieldOfView/20 * 0.5f * Mathf.Deg2Rad))); //cam.fieldOfView/20, I divide by 20 because I only need a small square of the view

    cubeVerts[0] = cam.transform.position + cam.transform.forward * 25; //25 is the distance from the camera to the object it follows
    cubeVerts[1] = cam.transform.position + cam.transform.forward * 25;
    cubeVerts[2] = cam.transform.position + cam.transform.forward * 25;
    cubeVerts[3] = cam.transform.position + cam.transform.forward * 25;
    cubeVerts[4] = cam.transform.position + (cam.transform.right * -frustumHeight) + (cam.transform.up * frustumHeight) + (cam.transform.forward * maxDistance);
    cubeVerts[5] = cam.transform.position + (cam.transform.right * frustumHeight) + (cam.transform.up * frustumHeight) + (cam.transform.forward * maxDistance);
    cubeVerts[6] = cam.transform.position + (cam.transform.right * -frustumHeight) + (cam.transform.up * -frustumHeight) + (cam.transform.forward * maxDistance);
    cubeVerts[7] = cam.transform.position + (cam.transform.right * +frustumHeight) + (cam.transform.up * -frustumHeight) + (cam.transform.forward * maxDistance);

    for (int i = 0; i < edges.Length; i += 2)
    {
        Debug.DrawLine(cubeVerts[edges[i]], cubeVerts[edges[i + 1]], Color.red);
    }

Here the altered frustum view follows the camera at any given time.


text:
Q: Using ID on HTML or BODY to set page-specific background image in CSS On a small currently unfinished bootstrap site (www.ehrenamt-ladenburg.de) I am trying to style the background image differently for each actual html file involved.
In my stylesheet for additional styling beyond bootstrap_3_3_1.css I am setting up the background image as a background url as in:
html {
    background: url(../images/tb20150807_210648_0216_8_0217_8_0218_8_0219_9_0220hdr-pm_1200.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

This works for HTML as well as BODY elements - but not for DIVs or lower level elements (to cover the full background for a responsive page).
Initially I had thought of referencing an additional page-specific CSS file in each html file involved just to style the html background for each of the few pages of the site (which seem a reasonable way of getting things done).
A google search brought me to Stackoverflow and the "Page-specific css rules - where to put them?" thread (and caused me to sign up immediately because of the quality of the question and answer exchange I found).
Now the question for the experienced folks (I am still fairly new to serious bootstrap and css programming):
Couldn't I find a way to reference some sort of page ID in my css selectors to restrict a certain background image to a certain page?
So my question, I guess, is: how can I style BODY element (or HTML element for that matter) with an ID and reference it in a page-specific way? What is the syntax? Or what am I doing wrong?
With:
<body id="03_eal">

in the html file neither:
body#03_eal {
  background: url(../images/tb20150614_081922_231.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

nor:
#03_eal body {
  background: url(../images/tb20150614_081922_231.jpg) no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

in the css file work for me.
Leaving out the ID portion in the css, it works fine using either BODY or HTML elements.
What would be the syntax? Or what am I doing wrong in trying to select HTML or BODY using an ID?

A: Since the body has an id already. There is no real reason to include the tag selector in your css. ID's should be unique and using that specific id can be called just like this
#some-id {
    someKey: someValue
}

And no need for doubt. If you have access to your pages, you are more than allowed to add a class or id to that page to make it standout visually different than other pages.
You can also wrap your content in every page with a  tag and pass your class or id that way as well.
Ok so the reason it does not work for you is that you are starting your css id with 0 which converts to a number. Try removing the 0. Never start any css selector with a number. Try adding the number as a suffix and your issue will be resolved

A: Include your image in body and that will work fine. No need of including id or class in body just add below code. But keep in mind that you are using background image for your website, so compress its size. It shouldn't be much heavy in size.
body{
margin : 0; //optional
padding : 0; //optional
background: url(../images/tb20150807_210648_0216_8_0217_8_0218_8_0219_9_0220hdr-pm_1200.jpg);
background-position:fixed;
background-repeat:no-repeat;
background-size:cover;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: propgress bar in notificationbar when app closed from background I am updating progress in notificaton bar in my application
when the app is closed or the task is interupted i want to show the message some thing went wrong How to do that?
(my progressbar is updating when the app is in foreground (not killed).)


text:
Q: Generate formatted friendly URL from RouteData I'm trying to programmatically map a query string to an SEO friendly route URL I've created within my RouteConfig.cs file but appear to be having difficultly.
My route configuration looks like this:
routes.MapRoute(
    name: "ReviewPost",
    url: "{year}/{month}/{filename}/",
    defaults: new {controller = "ReviewPost", action = "Detail"},
    namespaces: new[] {"ApplicationName.Website.Controllers"},
    constraints: new {year = @"\d{4}", month = @"\d{2}"}
);

And I'm able to retrieve the correct RouteData object like so:
string url = "~/ReviewPost/Detail/?year=2015&month=05&filename=review-title";
RouteData routeData = RouteDataUtils.RouteByUrl(myUrl);

However I'm having difficulty figuring out how to generate the friendly URL that should look like the one specified in my configuration (/2015/05/review-title/).
Is the RouteData object able to create an instance of the formatted URL above, or do I have to format it myself? Or does the MVC framework have a class for correctly formatting the URL string using the RouteData object?
Any help would be appreciated.

A: Update
Try it this way:
var urlHelper = new UrlHelper();
var theUrl = urlHelper.RouteUrl(routeData.Values);

original
Try something like this:
var urlHelper = new UrlHelper();
var theUrl = urlHelper.RouteUrl("ReviewPost",routeData.Values);

Note that the first parameter to RouteUrl is the name of your route--i.e. how you named it in MapRoute.


text:
Q: Is there a tool for automatic migrations on sequelize? I am working on a backend in Node.js / Sequelize for an iPhone application. I am wondering what the best solution is in 2020 to automate migrations in Sequelize.
I am also willing to change ORM if you recommend a better one than Sequelize that supports automatic migrations.

A: you can do this By using Synchronizing function of Sequelize
await sequelize.sync({ force: true });
console.log("All models were synchronized successfully.");

you check out this Doc of sequelize to for more use of sequelize.sync


text:
Q: Response.Redirect() Works in Visual Studio but not IIS I'm trying to upload a basic web application from visual studio on Windows 7 to an IIS environment on Windows Server 2007.
Though launching it from IIS displays the Login page, trying to navigate past it to the main menu returns this error:
Server Error in Application "PARKING/PARKING ASSIGNMENTS WEB"Internet Information Services 7.0
Error Summary
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable. Detailed Error Information
Module IIS Web Core
Notification MapRequestHandler
Handler StaticFile
Error Code 0x80070002
Requested URL http://localhost:81/Parking Assignments Web/Home
Physical Path C:\ParkingAssignmentsWeb\Home
Logon Method Anonymous
Logon User Anonymous
 Most likely causes:
•The directory or file specified does not exist on the Web server.
•The URL contains a typographical error.
•A custom filter or module, such as URLScan, restricts access to the file.
 Things you can try:
•Create the content on the Web server.
•Review the browser URL.
•Create a tracing rule to track failed requests for this HTTP status code and see which module is calling SetStatus. For more information about creating a tracing rule for failed requests, click here.
 Links and More InformationThis error means that the file or directory does not exist on the server. Create the file or directory and try the request again.
View more information »

This is the code I used for navigation:
Response.Redirect("Home.aspx");

Why would this navigation work on Visual Studio but not on IIS?
UPDATE: I tried the variations of the Redirect command you guys showed me but all of them gave a 404 error, which leads me to believe that the problem isn't with the command but with something else. Any idea what?

A: Please try:
Response.Redirect("~/Parking Assignments Web/Home.aspx");

or
Response.Redirect("~/Parking Assignments Web/Home");

A: It treats Home.aspx as a relative path.
Use it like:
Response.Redirect("/Home.aspx");

A: when you deploy to IIS a different web server is being used. Visual studio uses a web server with limited options and in most cases but not all an application should run without changes when deployed to IIS on windows server.
Things to check

*

*Verify that the folder structure on your workstation looks the same as the folder structure deployed to the server.

*check permissions on the folders accessed by IIS on the web server

*Response.Redirect("Home.aspx"); assumes that the file is in the same directory as the page that is invoking the transfer

*add a more complete path either ("/home.aspx") or ("/folder/home.aspx") where folder is the actual folder name that contains the .aspx file


text:
Q: AWS Snapshot Archiving AMI, and over 6 months old Does anyone know if its possible to retrieve a list of EC2 Snapshots that are standard tier, not attached to an AMI, and over 6 months old and make a list of them.
Any sort help would be appropriated ?


text:
Q: Orchard CMS Field Settings I have Custom Content Type in Orchard, with coresponding part of same name with two text fields, defined in migrations. The part definition is as follows:
ContentDefinitionManager.AlterPartDefinition("Faq",
           cfg => cfg
               .Attachable()
               .WithField("Question", f => f
                   .OfType("TextField")
                   .WithDisplayName("Question")
                   .WithSetting("Flavor","Wide"))
               .WithField("Answer", f => f
                   .OfType("TextField")
                   .WithDisplayName("Answer")
                   .WithSetting("Flavor", "Html"))

This adds the fields to the part, but the setting is not applied - both fields have the default flavor in the dashboard. I believe it is just a silly typo but I'm unable to figure it out.

A: Yeah, adding fields in migrations can be a little fiddly. What you really need is instead of just "Flavor", you need its fully qualified name, "TextFieldSettings.Flavor".
I've actually started adding a feature to Orchardizer (a VS extension) that will transform your export code into migrations code, so it'll build all that stuff for you. Should be done by the weekend (if I don't start feeling lazy)


text:
Q: Shipment Tracking displays Error in DHL Easylog Module I am using a DHL EasyLog Shipping Module
I use DHL International and DPD international Shipping and when I enter the shipping information on the Order I choose DHL  (Deprecated) and enter the tracking number.
On the customers end or admin end when I click on the tracking number it brings the Pop-Up up and gives the following:
Tracking Information
Tracking Number:  xxxxxxxxxx
Carrier:   DHL (Deprecated)
Error:  Tracking information is currently not available. Please contact us for more information or email us at Support@.........
Please advise!

A: So a wild guess is that this carrier method is not available or is actually deprecated. As the line in the file /app/code/core/Mage/Usa/etc/config.xml is as follows.
<specificerrmsg>This shipping method is currently unavailable. If you would like to ship using this shipping method, please contact us.</specificerrmsg>

Try using only the carrier with the code dhland label DHL and not the DHL (deprecated) version.
Note: there is an article from magento about installing the dhl deprecated if you need to use this version. http://www.magentocommerce.com/knowledge-base/entry/configure-dhl-shipping


text:
Q: Self-Hosted Gateway of API Manager 404 error Well I am having problems with the self-hosted gateway in an APIM.
I have followe this tutorials:

*

*For create an Azure API Management service: https://learn.microsoft.com/en-us/azure/api-management/get-started-create-service-instance

*For provisioning a self-hosted gateway: https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-provision-self-hosted-gateway

*For deploy it: https://learn.microsoft.com/en-us/azure/api-management/how-to-deploy-self-hosted-gateway-kubernetes
All go well and the self-hosted gateway is running, the LoadBalancer service is good and has an external IP... Even I have this green check:

However, when I visit the Gateway URL: https://apim-example.azure-api.net I got: { "statusCode": 404, "message": "Resource not found" } on the browser.
I dont know why, because I have a Hello world! API example deployed and asingned to the gateway and, if, insteal of make a GET on https://apim-example.azure-api.net/example/kenny, I make the GET using the public Load Balancer IP Of the self-hosted gateway (https://XX.XX.XX.XX/example/kenny) the API response a 200 OK.
Have anyone idea of how to solve this? A lot of thanks!

A: Following all the given Microsoft documentations, I have created an APIM Instance, Self-hosted Gateway in it and added the Kubernetes deployment in the Gateway:

Then I created the basic Http Trigger in the Azure Function App and imported it in the Azure APIM Instance by adding the Self-Hosted Gateway in the Settings of that API:

Note: For testing purpose, I have unchecked the "Subscription required" option.

However, when I visit the Gateway URL: https://apim-example.azure-api.netI got: { "statusCode": 404, "message": "Resource not found" } on the browser.

As given in this MS Doc, if we access the base URL without APIs, Response Status Code 404 will be displayed.

If API Name is passed to the Self-hosted gateway API of the APIM Instance, then the result is as expected:


text:
Q: How to install asterisk on Mac os for pjsip Does any one know how to install asterisk on mac? I am new to voip so please guide me from basics like what software/ command line tools would be needed.
I do tried to search it on google but couldn't found any doc with the proper steps. You can also provide link of tutorial. Thanks in advance.

A: Try brew it yourself brew asterisk

*

*minor issues in asterisk.rb and pjsip-asterisk.rb during brew

*change "<<-EOS.undent" to "<<~EOS" as suggest by brew solve the problem

-
xcode-select --install
brew tap leedm777/homebrew-asterisk
brew install asterisk

A: For novice in voip, recommended way is start virtulization system on your choice, run asterisk in container.
Not think you can find really upto-date tutorial for install asterisk on non-linux OS(windows,osx,solaris or linux-risk,linux-ARM, whatever). Such install required expert level on destination OS.


text:
Q: Nexus LDAP search in two Base DN In a Nexus LDAP integration I have to search in two 'Base DN'. under the 'Search Base', the one for real users and the other for functional users.
I tried Base DN (|(ou=a)(ou=b)) but not with the expected results.
Is there a way to provide and or relation ship between tow base DN keys or as alternative the possibility to search in two LDAP configurations?

A: There is no way to perform a single search limited to the scope of 2 base DNs in LDAP: One search - one base DN.
However, if your 2 base DNs share a common parent, you may search within a parent and try to limit the result set based on the attributes.
E.g. you have got ou=a,o=example, ou=b,o=example and ou=c,o=example. Assuming that sub-entries of all those 3 bases contain corresponding attribute ou with the matching value (in LDAP this is not ensured!!!), you could search within a base o=example with a filter (|(ou=a)(ou=b)).

A: Nexus Pro supports the definition of multiple LDAP connections for just this reason. You can query multiple search bases or even multiple servers by defining multiple connections.
If you are using Nexus OSS you will have to get your LDAP administrators to configure LDAP so that all desired user accounts are exposed via one search base.


text:
Q: Very custom date format in momentjs I am working with kibana (elasticsearch dashboard) which allow to specify a date pattern to explain the index naming pattern.
For instance, default pattern is: [logstash-]YYYY-MM-DD.HH
I'd like to organize my index by block of hours, let's say by block of 4 hours. Indices would then be named logstash-2014-02-25.00, logstash-2014-02-25.04, logstash-2014-02-25.08, …
Is there any way to get such format with momentjs ? I am dreaming of [logstash-]YYYY-MM-DD.{HH%4}
but the documentation does not explain such thing (how weird).

A: It seems impossible to do it with formatting primitives.
However, I found we can override some of the language-dependant formatter such as meridiem formatter.
A solution would then be to insert somewhere (in kibana conf file for example):
moment.lang('fourHourblocks', {
  meridiem: function(hour, minute, isLowercase) {
    hourBlock = Math.floor(hour / 4).toString();
    if (hourBlock.length < 2) hourBlock = "0" + hourBlock;
    return hourBlock;
  }
}

then I can set the pattern to [logstash-]YYYY-MM-DD.A.
This is kind of hacky so I am still opened to other solutions


text:
Q: Which should I be using: json-jquery or json2.js? I was curious if anyone here had a preference or if one library should definitely be used over the other? It seems that Json2.js is the "de-facto" standard. But JQuery-json is a jquery plugin. And since I'm using JQuery, I wondered which one should I be using.
JQuery-json and Json2.js

A: I'd suggest using Json2.js because it's a direct polyfill of the browser standard.
The JSON object is a built-in feature for all modern browsers. The only reason we need to use scripts like Json2.js is to support older browsers such as old versions of IE that don't have it built in. The syntax it provides is identical to the built-in JSON object in other browsers, and it doesn't override the built-in object if it already exists.
JQuery also uses the built-in JSON object where it's available as well, so at the end of the day, it's pretty much doing the same thing, but for browsers that already have the JSON object, using jQuery to wrap it means you're adding a layer of unnecessary syntax. You may or may not care about this, but that's pretty much the difference between them.

A: jQuery has had native JSON support for ages. Don't use a plugin for it.
Use json2.js if you aren't already using jQuery or another library that provides JSON support in old browsers.


text:
Q: 'Gradle cucumber' With testImplementation Not Working I am building a simple test app that uses cucumber. Unfortunately 'gradle cucumber' throws errors when I try to run it. However everything runs fine when  I change testImplement to the deprecated testCompile in build.gradle. Is this expected behaviour? What would I have to do to get cucumber to run using testImplementation?
build.gradle:
dependencies {
    testImplementation 'io.cucumber:cucumber-java:4.2.0'
    testImplementation 'io.cucumber:cucumber-junit:4.2.0'
}

configurations {
    cucumberRuntime {
        extendsFrom testRuntime
    }
}

task cucumber() {
    dependsOn assemble, compileTestJava
    doLast {
        javaexec {
            main = "cucumber.api.cli.Main"
            classpath = configurations.cucumberRuntime + sourceSets.main.output + sourceSets.test.output
            args = ['--plugin', 'pretty', '--glue', 'gradle.cucumber', 'src/test/resources']
        }
    }
}

Result (Error):
> Task :cucumber FAILED
Error: Could not find or load main class cucumber.api.cli.Main
Caused by: java.lang.ClassNotFoundException: cucumber.api.cli.Main

build.gradle:
dependencies {
    testCompile 'io.cucumber:cucumber-java:4.2.0'
    testCompile 'io.cucumber:cucumber-junit:4.2.0'
}
...

Result (Works):
> Task :cucumber
No features found at [src/test/resources]

0 Scenarios
0 Steps

Can someone explain what is going on here? Any help is greatly appreciated!

A: See here which says that testRuntime is deprecated

The compile, testCompile, runtime and testRuntime configurations inherited from the Java plugin are still available but are deprecated

I think it should be
configurations {
    cucumberRuntime {
        extendsFrom testImplementation
    }
}


text:
Q: Hibernate + Spring + JSF : Criteria.List() returning empty When MBean call the following getAll method, this method return empty.
@Repository("bookRepository")
@Transactional(propagation = Propagation.MANDATORY, readOnly = true)
public class BookRepositoryImpl implements BookRepository {

@Autowired
private SessionFactory sessionFactory;

@SuppressWarnings("unchecked")
public List<Book> getAll() {

    return getSession().createCriteria(Book.class).list();
}

private Session getSession() {
    return sessionFactory.getCurrentSession();
}

}
Book class:
@Entity
@Table(name = "book")
public class Book implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 2581522135048868175L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;
    @Column(name = "title", unique = true, nullable = false)
    private String title;
    @Column(name = "author", nullable = false)
    private String author;
    @Column(name = "isbn_code", unique = true, nullable = false, length = 10)
    private String isbnCode;
    @Column(name = "year")
    private Integer year;
    @Column(name = "price")
    private Double price;

    // Constructors

// Getters and Setters

}
application context:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                                               xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">

<context:annotation-config /> <!-- bean definitions go here -->
<context:component-scan base-package="br.com.myproject.faces">
    <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Controller" />
</context:component-scan>

<context:component-scan base-package="br.com.myproject.service.impl">
    <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Service" />
</context:component-scan>

<context:component-scan base-package="br.com.myproject.domain.model">
    <context:include-filter type="annotation"
        expression="org.springframework.stereotype.Repository" />
</context:component-scan>

<!-- HIBERNATE configuration INIT -->

<context:property-placeholder location="classpath:hibernate.properties" />

<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${jdbc.driverClassName}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan">
        <list>
            <value>org.camelcode.model</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            <!-- <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> -->
            <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
        </props>
    </property>
</bean>

<!-- HIBERNATE configuration END -->

Ps: I insert records in book table and all instances injected are OK.

A: Do you have this entry in your hibernate-config.xml
<property name="packagesToScan">
            <list>
                <value>Here you need to mention package name where your book class resides</value>
            </list>
        </property>

or need to mention mapping class like below
<mapping class="package.Book"/>

Are you missing these entries?


text:
Q: Custom validation help needed validate :check_product_stock
def check_product_stock

  @thisproduct = product.id

   @productbeingchecked = Product.find_by_id(@thisproduct)

   @stocknumber = @productbeingchecked.stock_number

  if producto.en_stock == 0
   raise "El Producto no tiene stock suficiente para completar la venta"

   #errors.add :venta, "Producto con pedos de stock"
   return false
  end
true
end

end

i need to be able to validate on creation of a model (sale), if it's association (product), hasn't reached zero in a product.column called stock_number.
i think i need to rewrite the entire thing but now with validate :check_product_stock then built a method from scratch that checks if product hasn't reached zero and it it has it should throw a flash notice and stay in the same place (sales/new)
class Venta < ActiveRecord::Base

  hobo_model # Don't put anything above this

  belongs_to :cliente, :accessible => true
  belongs_to :producto, :accessible => true
  belongs_to :marca, :accessible => true
  belongs_to :vendedor
  belongs_to :instalador
  has_many :devolucions

  fields do
    numero_de_serie     :string
    precio_de_venta      :integer
    precio_de_instalacion :integer, :default => "0"
    forma_de_pago enum_string(:contado, :tarjeta)
    status enum_string(:activa, :cancelada)
    timestamps
  end

  validates_presence_of :cliente, :precio_de_venta, :vendedor, :precio_de_instalacion

  validate_on_create :check_product_stock

  after_save :descontar_precio_de_instalacion_si_el_instalador_es_a_destajo

#def stock_error

  #flash[:notice] = "Producto con pedos de stock"

#  redirect_to :controller => :venta, :action => :stock_error

     #errors.add_to_base("Producto con pedos de stock")

 # end

def check_product_stock

if producto.en_stock == 0
 raise "El Producto no tiene stock suficiente para completar la venta"

 #errors.add :venta, "Producto con pedos de stock"
   return false
  end
true
end

#def check_product_stock
#  if producto.en_stock == 0
 #  errors.add :producto, "El Producto no tiene stock suficiente para completar la venta"
 #  return false
#  end
#  true # guards against returning nil which is interpreted as false.
#end

def descontar_precio_de_instalacion_si_el_instalador_es_a_destajo

  @este_instalador_id = instalador.id

  @instalador = Instalador.find_by_id(@este_instalador_id)

  if @instalador.a_destajo?

    @last_venta = Venta.find(:last)

    @vid = @last_venta.id

    @precio_de_instalacion_original = precio_de_instalacion

    @mitad_de_instalacion = @precio_de_instalacion_original/2

    #Venta.update(@vid, :precio_de_instalacion => @mitad_de_instalacion)

    ActiveRecord::Base.connection.execute "UPDATE ventas SET precio_de_instalacion = #{@mitad_de_instalacion} WHERE id = #{@vid};"

  end

end

#after_save :reduce_product_stock_number

# def reduce_product_stock_number
 #  Producto.decrement_counter(:en_stock, producto.id)
#  end

  # --- Permissions --- #

  def create_permitted?
    true
  end

  def update_permitted?
    false
  end

  def destroy_permitted?
    false
  end

  def view_permitted?(field)
    true
  end

end

And this is my observer that diminishes the en_stock column from producto:
class VentaObserver < ActiveRecord::Observer

def after_save(venta)

      @venta_as_array = venta

      if venta.producto_id?

      @pid = @venta_as_array[:producto_id]

      Producto.decrement_counter(:en_stock, @pid)

      end

      if venta.cart_id

        @cid = @venta_as_array[:cart_id]

        @cart = Cart.find_by_id(@cid)

        for item in @cart.cart_items do
         #  @pid = @cart.cart_items.producto.id

             Producto.decrement_counter(:en_stock, item.producto.id)

        end

        #si el instalador es a destajo se debe descontar la mitad del rpecio de instalacion

        end

end

end

A: It seems you've got a lot going wrong here.
First of all, you're doing way too much work. This is all you really need.
before_save :check_product_stock

def check_product_stock
  if product.stocknumber == 0
   flash[:notice] = "Producto con pedos de stock"
  end
end

Secondly, the flash hash is not available in models. You can use the ActiveRecord error object to make errors available to the controller and views by replacing
flash[:notice] = with errors.add_to_base
I used errors.add_to_base because the error is not exactly a part of this model, yet is still blocking the save.
Thirdly, it seems like you're reducing product.stocknumber at some point. Probably as a before_validation so it's highly possible that product.stocknumber is less than 0 during the check if product.stocknumber was 0 before the save call.
So let's change the if condition to reflect that.
unless product.stocknumber > 0

Finally, you're using a before_save callback, so just adding an error will not cancel the transaction. You need to return false for a before/after save/create/update/valdiaiton callback to cancel the transaction.
Putting this all together gives you
before_save :check_product_stock

def check_product_stock
  unless product.stocknumber > 0
   errors.add_to_base "Producto con pedos de stock"
   return false
  end
  true # guards against returning nil which is interpreted as false.
end

As for displaying these errors you can either use the nice error_messages_for helper on the object in the view. Or copy the errors to the flash hash in the controller.
In the view:
<%= error_mesages_for :order %>

Or, in the controller in the else block of if @order.save:
 flash[:errors] = @order.errors.full_messages.join "<br />"

I prefer the errors over notice when it comes to passing errors in the flash hash because it makes it easy to distinguish the two via CSS if an action happens to produce both a notices or an error. Also it's more DRY to always display flash[:errors] with a class that gives red text, the write the logic into your view to determine if the contents of flash[:notice] are an error or a notice.

A: flash is not available in the model. You need to do something like this:
errors.add :stocknumber, "Producto con pedos de stock"

And then work with flash in the controller and views.


text:
Q: Count specific character in each line of at text and remove this character in a specific position until this character has a specific count Hello i need help with one script that its on Solaris system:
I will explain the script analytically:
i have these files :
i)
cat /tmp/BadTransactions/TRANSACTIONS_DAILY_20180730.txt

    201807300000000004
    201807300000000005
    201807300000000006
    201807300000000007
    201807300000000008
    201807200002056422
    201807230003099849
    201807230003958306
    201806290003097219
    201806080001062012
    201806110001633519
    201806110001675603

ii)
cat /tmp/BadTransactions/test_data_for_validation_script.txt

20180720|201807200002056422||57413620344272|030341-213T |580463|WIRE||EUR|EUR|20180720|20180720|||||||00000000000019.90|00000000000019.90|Debit||||||||||MPA|||574000|129|||||||||||||||||||||||||31313001103712|BFNJKL|K| I P P BONNIER PUBLICATIO|||FI|PERS7
20180723|201807230003099849||57100440165173|140197-216U|593619|WIRE||EUR|EUR|20180723|20180723|||||||00000000000060.00|00000000000060.00|Debit||||||||||MPA|||571004|106|||||||||||||||||||||||||57108320141339|Ura Basket / UraNaiset|||-div|||FI|PERS
20180723|201807230003958306||57206820079775|210489-0788|593619|WIRE||EUR|EUR|20180721|20180723|||||||00000000000046.00|00000000000046.00|Debit||||||||||MPA|||578800|106|||||||||||||||||||||||||18053000009026|IC Kodit||| c/o Newsec Asset Manag|||FI|PERS
20180629|201806290003097219||57206820079775|210489-0788|593619|WIRE||EUR|EUR|20180628|20180629|||||||00000000000856.00|00000000000856.00|Debit||||||||||MPA|||578800|106|||||||||||||||||||||||||18053000009018|IC Kodit||| c/o Newsec Asset Manag|||FI|PERS
20180608|201806080001062012||57206820079441|140197-216S|580463|WIRE||EUR|EUR|20180608|20180608|||||||00000000000019.90|00000000000019.90|Debit||||||||||MPA|||541002|129|||||||||||||||||||||||||57108320141339|N FN|K| IKI I P BONNIER PUBLICATION|||FI|PERS7
20180611|201806110001633519||57206820079525|140197-216B|593619|WIRE||EUR|EUR|20180611|20180611|||||||00000000000242.10|00000000000242.10|Debit||||||||||MPA|||535806|106|||||||||||||||||||||||||57108320141339|As Oy Haikkoonsilta|| mannerheimin|||FI|PERS9
20180611|201806110001675603||57206820079092|140197-216Z|580463|WIRE||EUR|EUR|20180611|20180611|||||||00000000000019.90|00000000000019.90|Debit||||||||||MPA|||536501|129|||||||||||||||||||||||||57108320141339|N ^NLKL|K| I P NJ BONNIER PUBLICAT|||FI|PERS7

The script has to check each line of the
/tmp/BadTransactions/TRANSACTIONS_DAILY_20180730.txt and if the strings are on
the /tmp/BadTransactions/test_data_for_validation_script.txt it will create a
new file `/tmp/BadTransactions/TRANSACTIONS_DAILY_NEW_20180730.txt
From this new file it will count all the " | " in each line and if its more than 64 it will delete the " | " in 61th posistion of the line . This will be continued until its line has 64 pipes.
For example if one line has 67 " | " it will delete the 61th , then it will check it again and now has 66 " | | so it will delete the 61th " | " , etc... until it reach 64 pipes.So all the line have to have 64th " | ".
Here is my code , but in this code i have managed to delete only the 61th pipe in each line , i cannot make the loop so that it will check each line until it reach the 64 pipes.
I will appreciate it if you could help me.
#!/bin/bash
PATH=/usr/xpg4/bin:/bin:/usr/bin

while read line
do

grep "$line" /tmp/BadTransactions/test_data_for_validation_script.txt

awk 'NR==FNR { K[$1]; next } ($2 in K)' /tmp/BadTransactions/TRANSACTIONS_DAILY_20180730.txt FS="|" /opt/NorkomC
onfigS2/inbox/TRANSACTIONS_DAILY_20180730.txt > /tmp/BadTransactions/TRANSACTIONS_DAILY_NEW_20180730.txt

sed '/\([^|]*[|]\)\{65\}/ s/|//61' /tmp/BadTransactions/TRANSACTIONS_DAILY_NEW_20180730.txt

done < /tmp/BadTransactions/TRANSACTIONS_DAILY_20180730.txt > /tmp/BadTransactions/TRANSACTIONS_DAILY_NEW_201807
30.txt

A: Ok, in this problem you have several pieces of code.

*

*You need to read a file line by line

*Check each line against another file

*Examine the matching line for the occurrences of "|"

*Delete recursively the 61st "|" until the string will remain with 64 of them

You could do something like this
#!/bin/bash
count() { ### We will use this to count how many pipes are there
  string="${1}"; shift
  char="${1}"
  printf "%s" "${string}" | grep -o -e "${char}" | grep -c .
}
file1="/tmp/BadTransactions/TRANSACTIONS_DAILY_20180730.txt" ### File to read
file2="/tmp/BadTransactions/test_data_for_validation_script.txt" ### File to check for duplicates
file3="/tmp/BadTransactions/TRANSACTIONS_DAILY_NEW_20180730.txt" ### File where to save our final work
printf "" > "${file3}" ### Delete (eventual) history
exec 3<"${file1}" ### Put our data in file descriptor 3
while read -r line <&3; do ### read each line and put it in var "$line"
  string="$(grep -e "${line}" "${file2}")" ### Check the line against second file
  while [ "$(count "${string}" "|")" -gt 64 ]; do ### While we have more than 64 "|"
    string="$(printf "%s" "${string}" | sed -e "s/|//61")" ### Delete the 61st occurrence
  done
  printf "%s" "${string}" >> "${file3}" ### Save the correct line in the third file
done
exec 3>&- ### Clean file descriptor 3

This is not tested, but should work.
N.B. Please note that I am giving for granted that grep will return only one occurrence from second file...
If it is not your case you have to manually check each value with something like:
for value in $(grep -e "${line}" "${file2}"); do
  ...
done

EDIT:
For systems like Solaris or others that doesn't have GNU grep installed you can substitute the count method as follow:
count() {
  string="${1}"; shift
  char="${1}"
  printf "%s" "${string}" | awk -F"${char}" '{print NF-1}'
}


text:
Q: Java 8 "Missing return type" error for lambda expression I am new to Java 8 and trying to understand the concepts. I am getting
Missing return type

error for the Lambda expression I am passing to ReadTheFile method.
BufferReaderProcessor
package java8.programs;

import java.io.BufferedReader;
import java.io.IOException;

@FunctionalInterface
public interface BufferReadderProcessor {
    String process(BufferedReader br) throws IOException;
}

MainJava
package java8.programs;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class MainJava {
    public static void main(String[] args) throws IOException {
        MainJava obj = new MainJava();

        String message = obj.ReadTheFIle((BufferedReader br) -> {
                while (br.readLine()!=null)
                    br.readLine();
        });
        System.out.println(message);
    }

    public String ReadTheFIle(BufferReadderProcessor bp) throws IOException {
        BufferedReader br = new BufferedReader(new FileReader(new File("G:\\DemoJavaFile.txt")));

        return bp.process(br);
    }
}

A: Your lambda expression implements the BufferReaderProcessor's String process(BufferedReader br) method, so it should return a String.
For example, assuming you wish to return the data you read from the BufferedReader :
    String message = obj.ReadTheFIle((BufferedReader br) -> {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            sb.append(line);
            line = br.readLine();
        }
        return sb.toString();
    });


text:
Q: trim() expects parameter 1 to be string Got a situation with image import process, before asking here of course - tried many ways to solve it by myself, but without any luck yet.
I'm getting error in model file: trim() expects parameter 1 to be string, array given in file /.../file.php on line 3875. Have to mention that - when there's single image - importing that perfectly, as soon as getting multiple images (more than one) - getting this error, and doesn't importing any image, just skipping.
Line 387:  $image = trim($image);
Whole function code:
    protected function imageHandler($field, &$config, $multiple = false, $item_id = NULL) {
    $image_array = array();

    if (empty($config['columns'][$field])) {
      if ($multiple) {
        return $image_array;
      } else {
        return '';
      }
    }

    $sort_order = 0;

    foreach ((array) $config['columns'][$field] as $images) {

      if (!empty($config['multiple_separator']) && is_string($images)) {
        $images = explode(@html_entity_decode($config['multiple_separator']), $images);
      }

      //is_array($images) && reset($images);

      if ($multiple && is_array($images) && $config['columns']['image'] == $images[key($images)]) {
        array_shift($images);
      }

      foreach ((array) $images as $image) {
        $image = trim($image);

        if ($config['image_download'] && $image) {
          // if (substr($image, 0, 2) == '//') {
            // $image = 'http:' . $image;
          // }

          $file_info = pathinfo(parse_url(trim($image), PHP_URL_PATH));

          // if no extension, get it by mime
          if (empty($file_info['extension'])) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, trim($image));
            curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_NOBODY, 1);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_exec($ch);
            $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);

            switch($contentType) {
              case 'image/bmp': $file_info['extension'] = 'bmp'; break;
              case 'image/gif': $file_info['extension'] = 'gif'; break;
              case 'image/jpeg': $file_info['extension'] = 'jpg'; break;
              case 'image/pipeg': $file_info['extension'] = 'jfif'; break;
              case 'image/tiff': $file_info['extension'] = 'tif'; break;
              case 'image/png': $file_info['extension'] = 'png'; break;
              default: $file_info['extension'] = '';
            }
          }

          if (substr_count($file_info['dirname'], 'http')) {
            // incorrect array extract
           if (!$multiple) {
              return $image;
            } else {
              $image_array[] = $image;
              continue;
            }
          }

          if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
            $this->session->data['obui_log'][] = array(
              'row' => $this->session->data['obui_current_line'],
              'status' => 'error',
              'title' => $this->language->get('warning'),
              'msg' => $this->language->get('warning_incorrect_image_format') . ' ' . str_replace(' ', '%20', $image),
            );

            if (!$multiple) {
              return $image;
            } else {
              $image_array[] = $image;
              continue;
            }
          }

          if ($this->simulation) {
            if (!$multiple) {
              /* Now handled before
              if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
                return array('error_format', $image);
              }*/
              return $image;
            } else {
              /* Now handled before
              if (!in_array(strtolower($file_info['extension']), array('gif', 'jpg', 'jpeg', 'png'))) {
                $image_array[] = 'error_format';
                continue;
              }*/
              $image_array[] = $image;
              continue;
            }
          }

          // detect if image is on actual server
          if (strpos($image, 'http') === false) {
            $filename = trim($image);

            if (!$multiple) {
              return $filename;
            } else {
              if (!empty($filename)) {
                $image_array[] = array(
                  'image' => $filename,
                  'sort_order' => $sort_order++,
                );
              }
              continue;
            }
          }

          if (version_compare(VERSION, '2', '>=')) {
            $path = 'catalog/';
            //$http_path = HTTP_CATALOG . 'image/catalog/';
          } else {
            $path = 'data/';
            //$http_path = HTTP_CATALOG . 'image/data/';
          }

          if (trim($config['image_location'], '/\\')) {
            $path .= trim($config['image_location'], '/\\') . '/';
          }

          if ($config['image_keep_path'] && trim($file_info['dirname'], '/\\')) {
            $path .= trim($file_info['dirname'], '/\\') . '/';
          }

          if (!is_dir(DIR_IMAGE . $path)) {
            mkdir(DIR_IMAGE . $path, 0777, true);
          }

          $filename = $path . urldecode($file_info['filename']) . '.' . $file_info['extension'];

          if (($item_id === false && $this->config->get('mlseo_insertautoimgname')) || ($item_id && $this->config->get('mlseo_editautoimgname'))) {
            $this->load->model('tool/seo_package');
            $seo_image_name = $this->model_tool_seo_package->transformProduct($this->config->get('mlseo_product_image_name_pattern'), $this->config->get('config_language_id'), $config['columns']);

            $seoPath = pathinfo($filename);

            if (!empty($seoPath['filename'])) {
              $seoFilename = $this->model_tool_seo_package->filter_seo($seo_image_name, 'image', '', '');
              $filename = $seoPath['dirname'] . '/' . $seoFilename . '.' . $seoPath['extension'];

              if (file_exists(DIR_IMAGE . $filename)) {
                $x = 1;

                while (file_exists(DIR_IMAGE . $filename)) {
                  $filename = $seoPath['dirname'] . '/' . $seoFilename . '-' . $x . '.' . $seoPath['extension'];
                  $x++;
                }
              }
            }
          }

          if ($config['image_exists'] == 'rename') {
            $x = 1;
            while (file_exists(DIR_IMAGE . $filename)) {
              $filename = $path . urldecode($file_info['filename']) . '-' . $x++ . '.' . $file_info['extension'];
            }
          } else if ($config['image_exists'] == 'keep' && file_exists(DIR_IMAGE . $filename)) {
            // image skipped
            if (!$multiple) {
              return $filename;
            } else {
              $image_array[] = array(
                'image' => $filename,
                'sort_order' => $sort_order++,
              );

              continue;
            }
          }

          // copy image, replace space chars for compatibility with copy()
          // if (!@copy(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename)) {
          $copyError = $this->copy_image(trim(str_replace(' ', '%20', $image)), DIR_IMAGE . $filename);

          if ($copyError !== true) {
            if (defined('GKD_CRON')) {
              $this->cron_log($this->session->data['obui_current_line'] . ' - ' . $copyError);
            } else {
              $this->session->data['obui_log'][] = array(
                'row' => $this->session->data['obui_current_line'],
                'status' => 'error',
                'title' => $this->language->get('warning'),
                'msg' => $copyError,
              );
            }

            $filename = '';
          }

        } else {
          // get direct value
          $filename = trim($image);

          if ($this->simulation) {
            if (!$multiple) {
              return $filename;
            } else {
              if (!empty($filename)) {
                $image_array[] = $filename;
              }
              continue;
            }
          }
        }

        // one field only, directly return first value
        if (!$multiple) {
          return $filename;
        }

        if (!empty($filename)) {
          $image_array[] = array(
            'image' => $filename,
            'sort_order' => $sort_order++,
          );
        }
      }
    }

    return $image_array;
  }

Tried to use return $image; after that line, even that didn't helped. Was trying to find similar problem to this one to find a solution without posting here, but seems like I won't move anywhere withou help. Thanks in advance!


text:
Q: Apply template by path/slug related to custom post type? I have a custom post type called "project" and an accompanying single view template labeled single-project.php On the landing page for each project, I have sub-navigation that points to separate sub-sections that query related items such as "Related Projects" and "Related Resources". Is there a way I can create templates to handle these pages based on the path and custom post type? For instance, if a project is labeled "Test Project" and the sub-nav URL points to test-project/related-resources, is there a way for me to create a template that would handle related-resources automatically by referencing the path/slug along with the custom post type?
Thanks for any insight here.

A: You can't set a project as a base of permalink because you would have to enter rewrite rules for each one.
What you can do is create a custom taxonomy related-resources:
function wpse_287202_related_resources_taxonomy() {

    $labels = array(
       ...
    );

    $args = array(
        'labels'                     => $labels,
        'hierarchical'               => true,
        'public'                     => true,
        'show_ui'                    => true,
        'show_admin_column'          => true,
        'show_in_nav_menus'          => true,
        'show_tagcloud'              => true,
    );
    register_taxonomy( 'related-resources', array( 'product', 'post', 'page' ), $args );

}
add_action( 'init', 'wpse_287202_related_resources_taxonomy', 0 );

It needs to be associated with your product custom post type and posts, pages or other custom post types you want to add to related resources. You do that by changing the second parameter of register_taxonomy.
In your product custom post type add related-resources to taxonomies:
'taxonomies' => array( 'related-resources' ),

Now when you edit project add "Amazing Project 17" to related resources taxonomy the same way as you would add a category and check it just for the project it relates to. In this setup, you can't have a project be a related resource to other project but that could be changed.
In every post, page or custom post type other than project you associated with the taxonomy, you can select "Amazing Project 17" and it will be displayed as a related resource for that particular project.

Now you need to display it all and to know what template to use check WP Hierarchy. Related resources will be displayed using taxonomy-related-resources.php file. There just make sure to exclude project from displaying as it is part of the related resources taxonomy, do it by checking get_post_type().
To display link to related resources on the project page use:
$term = get_the_terms( $post->ID, 'related-resources' )[0];
echo '' . __( 'Related Resoucrces', 'text_domain' ) . '';

If things seem confusing read more about custom taxonomies and how they can be used with custom post types.


text:
Q: Linq to SQL joining two tables and populate GridView I have two tables in my database, Building and Town. They look like this:
Building:
buildingid
buildingname

Town:
id
userid
buildingid

In Town there is one entry for each building a user has.
What i want is to populate a GridView for a user with a given userid. This GridView should include the buildingname and the number of buildings.
Building. I have tried this:
var buildings = (from Town in dc.Towns
                         join Building in dc.Buildings
                             on Town.buildingid equals Building.buildingid
                         select Building.buildingname);
        gvBuildings.DataSource = buildings;
        gvBuildings.DataBind();

But I don't know how to get the numbers for each building.

I have now been working on this for a while and a couple of your answers work. I have used this code:
var buildings = dc.Towns
            .Where(t => t.userid == userid)
            .GroupJoin(dc.Buildings,
                       t => t.buildingid,
                       b => b.buildingid,
                       (Town, Buildings) => new
                                                {
                                                    BuildningName = Buildings.First().buildingname,
                                                    Count = Buildings.Count()
                                                });
        gvBuildings.DataSource = buildings.ToList();
        gvBuildings.DataBind();

When i run this code my GridView ends up looking like this:

I need the buildings to be shown in groups, grouped by the buildingname. I have tried all of the suggestions but i cant get it to work.

A: check linq differed execution
and than try the blow code might work for you
    var buildings =

(from j in dc.Town
join i in dc.Buildings
 on j.buildingId equals i.buildingId
where j.Userid = varUSerid
group new {i, j}
by new
{   i.BuildingID }
into
g
select new {
  BuildingName = g.First<k=>k.BuildingName)
   , count = g.Count() } ).ToList();
    gvBuildings.DataSource = buildings;
          gvBuildings.DataBind();

A:  var buildings = (from Town in dc.Towns
                                 join Building in dc.Buildings
                                     on Town.buildingid equals Building.buildingid
                                 into results
                                 from r in results.DefaultIfEmpty()
                                 group Town by new
                                 {
                                     r.BuildingId
                                 } into groupedResults
                                 where Town.UserID == parameteruserId
                                 select new
                                 {
                                     BuildingName = Building.buildingname,
                                     BuildingCount = groupedResults.Count()
                                  });

Try this.. it should work.. i have a similar requirement..

A: Try grouping:
var buildings = dc.Towns
                  .Where(t => t.UserId == userId)
                  .GroupJoin(dc.Buildings,
                             t => t.BuildingId,
                             b => b.BuildingId,
                             (town, buildings) => new
                             {
                                 BuildingName = buildings.First().BuildingName,
                                 Count = buildings.Count
                             });

Keep in mind that when binding to a control you must supply a collection of type (or implementing) IList. This can be accomplished by calling ToList() on the buildings collection:
gvBuildings.DataSource = buildings.ToList();
gvBuildings.DataBind();

A:  manDbDataContext db = new DbDataContext();

 var estimatedTotal = (  from est in db.AssignmentEstimatedMaterials
                         where est.assignment_id == Convert.ToInt32(Label_assignmentId.Text)
                         join materialdetail in db.Materials on est.material_id equals materialdetail.material_id
                         select new { est.qty,est.total_amount, materialdetail.material_name}).ToList();

    GridView_estiamte_material.DataSource = estimatedTotal;
    GridView_estiamte_material.DataBind();

Note, you should select individual data and it works.


text:
Q: Enabling Notes and Attachments after custom object creation When I first started our custom object Request_for_System_Change, I didn't check the box to allow Add Notes and Attachments – and according to the documentation SALESFOREC.com - Fields for Defining Custom Objects
 this option is only available when creating new custom objects
so is there an Apex or VF way to do this?

A: This checkbox simply saves you the trouble of having to drag the Notes and Attachments related list onto the page layout.
Here I forget to do this on creating my new object. Oh no!

If I go to the UI for my new object, sure enough, no notes and attachments related list.

Go to your page layout, find the related lists. In there you will find the related list for "Notes and Attachments".

Drag that onto the related list part of the page layout.

You're all set. No worries.


text:
Q: Combine toggle and fadeTo in jquery Is there a way I can toggle the fadeTo() method in jquery? Does a specific method exist for this or do I have to use conditionals to achieve that?

A: There's a method specifically for this - the .fadeToggle() method:

$(document).ready(function() {
  $("button").click(function() {
    $("p").fadeToggle();
  });
});

<button>Toggle</button>

This is a paragraph.

Hope this helps! :)


text:
Q: find multiple different strings and replace them How can I find multiple different strings in a file and replace them all with the same string?
For example, I have a file that looks like this:
.revicon-search-1:before
.revicon-pencil-1:before
.revicon-picture-1:before

I fould like to find .revicon-picture-1:before and .revicon-search-1:before and replace it with SOMETHING. The number of strings I would like to replace is 100-1000.
How can I achieve this? I am on mac.


text:
Q: How to create a PK by summing a column value and a self-increasing I'm working on an ETL and I need to create a new table. This table has no PK in the source so I must create it in my Staging.
This is the query from where I extract the data:
SELECT PP.PRVECODI,
       VW.GRUPDESC,
       VW.FAMIDESC,
       PP.ARTICODI,
       VW.ARTIDESC,
       PP.PROVREFER,
       PP.PPLNMARCA,
       PP.PPLNORIGEN,
       ( SELECT COUNT(1)
         FROM   CPR05.ACUERDOSCOMPRA AC
         WHERE AC.ARTICODI = VW.ARTICODI
         AND   AC.ACUCDESDE <= TRUNC(SYSDATE)
         AND   AC.ACUCHASTA >= TRUNC(SYSDATE)
         AND AC.PRVECODI = PP.PRVECODI ) ACUERDOS,VW.SBFMDESC
FROM   CPR05.SAC_VWARTICULOS VW
       INNER JOIN (
         SELECT DISTINCT
                ARTICODI,
                PL.PROVREFER,
                PL.PPLNMARCA,
                PL.PPLNORIGEN,
                P.PRVECODI
         FROM   CPR05.PROPUESTASLINEAS PL
                INNER JOIN CPR05.PROPUESTAS P
                ON (P.PPTACODI = PL.PPTACODI)
                   AND P.PPTAFECFIN >= TRUNC(SYSDATE)
       ) PP
       ON (VW.ARTICODI=PP.ARTICODI)
ORDER BY
       VW.GRUPDESC,
       VW.FAMIDESC,
       VW.ARTIDESC

I need to create a Table to insert this query and the PK must be a combination between the PP.ARTICODI column and a self-increasing integer.
I have tryed to combine the identity column with the ARTICODI but its not working:
CREATE TABLE CENTRALCOMPRASSTG..ProveedoresCatalogo(
  IDProveedoresCatalogo INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
  PRVECODI NUMERIC(9,0),
  GRUPDESC NVARCHAR(40),
  FAMIDESC NVARCHAR(40),
  ARTICODI NUMERIC(9,0),
  PROVREFER NVARCHAR(20),
  PPLNMARCA NVARCHAR(20),
  PPLNORIGEN NVARCHAR(50),
  ACUERDOS INT,
  SBFMDESC NVARCHAR(40)
)

Expected output
Thanks in advance

A: In Oracle 12c and later, you can use an IDENTITY column to generate the unique value and then a virtual column to combine it with the ARTICODI column:
CREATE TABLE ProveedoresCatalogo (
  IDProveedoresCatalogo INT
                        GENERATED ALWAYS AS IDENTITY(
                                              START WITH   1000000
                                              INCREMENT BY 1000000
                                            )
                        PRIMARY KEY
                        NOT NULL,
  ExpectedPK            INT
                        GENERATED ALWAYS AS ( IDProveedoresCatalogo + ARTICODI )
                        UNIQUE,
  ARTICODI              NUMBER(6,0) NOT NULL, -- Ensure this is only 6 digits
  PRVECODI              NUMBER(9,0),
  GRUPDESC              NVARCHAR2(40),
  FAMIDESC              NVARCHAR2(40),
  PROVREFER             NVARCHAR2(20),
  PPLNMARCA             NVARCHAR2(20),
  PPLNORIGEN            NVARCHAR2(50),
  ACUERDOS              INT,
  SBFMDESC              NVARCHAR2(40)
)

Then, if you:
INSERT INTO ProveedoresCatalogo ( ARTICODI, PRVECODI )
SELECT 700002, 13757 FROM DUAL UNION ALL
SELECT 700002, 10561 FROM DUAL UNION ALL
SELECT 700002, 51212 FROM DUAL;

Then:
SELECT IDProveedoresCatalogo,
       ExpectedPK,
       ARTICODI,
       PRVECODI
FROM   ProveedoresCatalogo

Outputs:

IDPROVEEDORESCATALOGO | EXPECTEDPK | ARTICODI | PRVECODI
--------------------: | ---------: | -------: | -------:
              1000000 |    1700002 |   700002 |    13757
              2000000 |    2700002 |   700002 |    10561
              3000000 |    3700002 |   700002 |    51212

db<>fiddle here

In SQL Server:
CREATE TABLE ProveedoresCatalogo (
  IDProveedoresCatalogo INT
                        IDENTITY( 1000000, 1000000 )
                        PRIMARY KEY
                        NOT NULL,
  ExpectedPK            AS ( IDProveedoresCatalogo + ARTICODI )
                        UNIQUE,
  ARTICODI              NUMERIC(6,0) NOT NULL, -- Ensure this is only 6 digits
  PRVECODI              NUMERIC(9,0),
  GRUPDESC              NVARCHAR(40),
  FAMIDESC              NVARCHAR(40),
  PROVREFER             NVARCHAR(20),
  PPLNMARCA             NVARCHAR(20),
  PPLNORIGEN            NVARCHAR(50),
  ACUERDOS              INT,
  SBFMDESC              NVARCHAR(40)
)

db<>fiddle here

A: You could use a computed column for that:
CREATE TABLE CENTRALCOMPRASSTG..ProveedoresCatalogo(
  InternalIdentityID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
  IDProveedoresCatalogo = CAST(CONCAT(InternalIdentityID, ARTICODI) AS INT),
  PRVECODI NUMERIC(9,0),
  GRUPDESC NVARCHAR(40),
  FAMIDESC NVARCHAR(40),
  ARTICODI NUMERIC(9,0),
  PROVREFER NVARCHAR(20),
  PPLNMARCA NVARCHAR(20),
  PPLNORIGEN NVARCHAR(50),
  ACUERDOS INT,
  SBFMDESC NVARCHAR(40)
)

or (maybe this one is faster):
CREATE TABLE CENTRALCOMPRASSTG..ProveedoresCatalogo(
  InternalIdentityID INT IDENTITY(1,1) PRIMARY KEY NOT NULL,
  IDProveedoresCatalogo = InternalIdentityID * POWER(10, LEN(ARTICODI)) + ARTICODI,
(...)


text:
Q: Cannot calculate tripcost, complains about NoneType instead def hotelcost(nights):
    cost = 140
    return nights * cost

def planeridecost(city):
    if city == "Charlotte":
        return 183
    elif city == "Tampa":
        return 220
    elif city == "Pittsburgh":
        return 222
    elif city == "Los Angeles":
        return 475

def rentalcarcost(days):
    cost = 40 * days
    if days >= 7:
        cost - 50
    elif days >= 3:
        cost - 20
    else:
        return cost
def tripcost(city,days,spendingmoney):
    return planeridecost(city) + hotelcost(days) + rentalcarcost(days) + spendingmoney
    print tripcost
    return tripcost

tripcost("Los Angeles",5,600)

I cannot solve this problem in Python. I have tried several other codes to do same operation but I can't execute:
Traceback (most recent call last):
  File "python", line 28, in <module>:
  File "python", line 25, in tripcost:
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

A: Your rentalcarcost() function only returns the cost value in one of the branches:
def rentalcarcost(days):
    cost = 40 * days
    if days >= 7:
        cost - 50
    elif days >= 3:
        cost - 20
    else:
        return cost

So only if days is smaler than 3 will you return a cost. The other branches need to include return statements too, or you'll end up returning None instead:
def rentalcarcost(days):
    cost = 40 * days
    if days >= 7:
        return cost - 50
    elif days >= 3:
        return cost - 20
    else:
        return cost

A: Rentalcarcost function returns None for cases where days>=7 and days>=3.Do it like below:
def rentalcarcost(days):
    cost = 40 * days
    if days >= 7:
        return (cost - 50)
    elif days >= 3:
        return (cost - 20)
    else:
        return cost

Your tripcost function has 2 returns and the second one is useless.


text:
Q: C++: Should I be using Boost.Date_Time Posix Time or Local Time? I'm making changes to an existing multiplatform library.  The library currently uses time_t and time(NULL) to store "timestamps" of important events, but the seconds-resolution is no longer enough.  The library already uses Boost for different things, so I was looking at converting all the time_t timestamps into one of the Boost.Date_Time objects.
But I'm a bit confused between "Posix Time" and "Local Time".  Is the only difference that Local Time also includes a timezone?  It seems that a ptime object can be converted to a local_date_time object by providing a timezone to use.
Am I right in thinking I should use ptime for storing the timestamps, and let clients/callers decide themselves if they want to convert to local_date_time if they require it?

A: Short answer:
Yes, boost ptime will be the closest equivalent to a time_t; both are a seconds since Epoch/beginning of recorded time kind of representation. And Boost ptime can be freely converted to a Boost local_date_time given a timezone.
The normal use will be to store the Universal timestamp and convert it into a locally meaningful time for display on demand. So,
An east coast server might record some event, at the local time 2012-02-12 17:05 EST, which translates into the prime/time_t internal representation of seconds since Epoch as 2012-02-13 00:05 UTC and put that into the database. Then the Paris client can convert to local_date_time/struct tm as 2012-02-13 01:05 CET and the San Francisco client to 2012-02-12 13:05 PST.
Longer answer: (Probably not relevant to your application which is already standardized on time_t)
But on some occasions, you might store the local date time directly if the geographic component has some meaning. You might imagine many event sources around the world and it might be interesting to know whether those events are day-time or night-time locally. You might recover that 1 of 2 ways. Either store a local date time/struct tm directly/or other datetime offset/timezone type that retains the originating timezone and local time, e.g. 14:00 PST (daytime) or 03:05 CET (nighttime).
Or store the event with some ref to the originating source so the timezone can be recovered. But given maintenance that may delete the source, or the lack of any straightforward join, it's often easier than trying to reverse engineer whatever geographic info might be saved back into a timezone.


text:
Q: Non delimited file on delimited file My file is :
07/15/19 02:58:40 PM   toto2_UBD_FD_GPRS_GLBL_EXCP   TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            0
07/15/19 02:58:40 PM   toto_UBD_FD_GPRS_GLBL_EXCP    TABLE         DATA    COMPLETE   BASE_TEST_DSA   37484032     253118
07/15/19 02:55:59 PM   UBD_FD_GPRS_GLBL_EXCP         TABLE         DATA    COMPLETE   BASE_TEST_DSA   37484032     253118
07/15/19 02:55:59 PM   UBV_FD_GSM_GLBL_EXCP          TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            0

I expected
07/15/19 02:58:40 PM;toto2_UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;0;0;;
07/15/19 02:58:40 PM;toto_UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;37484032;253118;;
07/15/19 02:55:59 PM;UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;37484032;253118;;
07/15/19 02:55:59 PM;UBV_FD_GSM_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;0;0;;

I tried
 sed -e 's/   /;/g'
or
awk -F'   ' -v OFS=';' '{$1=$1}1' file
The result is :
07/15/19 02:58:40 PM;toto2_UBD_FD_GPRS_GLBL_EXCP;TABLE;;;DATA; COMPLETE;BASE_TEST_DSA;0;;;;0;;;;;;;;;;;;;
07/15/19 02:58:40 PM;toto_UBD_FD_GPRS_GLBL_EXCP; TABLE;;;DATA; COMPLETE;BASE_TEST_DSA;37484032;  253118;;;;;;;;;;;
07/15/19 02:55:59 PM;UBD_FD_GPRS_GLBL_EXCP;;;TABLE;;;DATA; COMPLETE;BASE_TEST_DSA;37484032;  253118;;;;;;;;;;;
07/15/19 02:55:59 PM;UBV_FD_GSM_GLBL_EXCP;;; TABLE;;;DATA; COMPLETE;BASE_TEST_DSA;0;;;;0;;;;;;;;;;;;;

I need to put this data into a table, with 10 delimited fields. So I need 9 semicolons on my file, otherwise i cant load my file. The difficulty for me here, is the last two colons, It's error code and error text, it can be null. It's NULL in my exemple file. The other difficulty is the whitespace, there is not delimiter between the data in source file.

A: For the original data
Judging from the data shown, the input file has three blanks between columns.  Therefore, a sed script is appropriate:
sed -e 's/   /;/g'

Replace sequences of three blanks with a semicolon, all the way along the line.
The fact that line 3 has more columns than the other lines is likely be a headache when loading the data into a database — if that's what you mean by 'import'.
The code makes no attempt to handle pre-existing semicolons in the data.
Original data:
07/15/19 02:58:40 PM   toto2   TABLE   DATA   COMPLETE   BASE_TEST   0   0
07/15/19 02:58:40 PM   toto   TABLE   DATA   COMPLETE   BASE_TEST   37484032   253118
07/15/19 02:55:59 PM   UBD   TABLE   DATA   COMPLETE   BASE_TEST   32   2   CORERROR   LIBLERROR
07/15/19 02:55:59 PM   UBV   TABLE   DATA   COMPLETE   BASE_TEST   0   0

When I copied the data from the question, I found that lines 1, 2, 4 each had 6 trailing blanks.  The sed script produced:
07/15/19 02:58:40 PM;toto2;TABLE;DATA;COMPLETE;BASE_TEST;0;0;;
07/15/19 02:58:40 PM;toto;TABLE;DATA;COMPLETE;BASE_TEST;37484032;253118;;
07/15/19 02:55:59 PM;UBD;TABLE;DATA;COMPLETE;BASE_TEST;32;2;CORERROR;LIBLERROR
07/15/19 02:55:59 PM;UBV;TABLE;DATA;COMPLETE;BASE_TEST;0;0;;

Note that there are two trailing semicolons on those lines, for the empty fields containing CORERROR and LIBLERROR in line 3.  So, it appears that the data does have a uniform number of fields after all.   Trailing spaces are remarkably hard to spot!

For the revised data
The original data had a uniform 3-spaces between fields.  The revised data has a non-uniform number of spaces between fields — from 3 upwards.  That can be handled in sed using:
sed -e 's/ \{3,\}/;/g'

The only problem is now that adjacent empty fields can't be distinguished.
On the data:
07/15/19 02:58:40 PM   toto2_UBD_FD_GPRS_GLBL_EXCP   TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            0
07/15/19 02:58:40 PM   toto_UBD_FD_GPRS_GLBL_EXCP    TABLE         DATA    COMPLETE   BASE_TEST_DSA   37484032     253118
07/15/19 02:55:59 PM   UBD_FD_GPRS_GLBL_EXCP         TABLE         DATA    COMPLETE   BASE_TEST_DSA   37484032     253118
07/15/19 02:55:59 PM   UBV_FD_GSM_GLBL_EXCP          TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            0

The output is:
07/15/19 02:58:40 PM;toto2_UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;0;0
07/15/19 02:58:40 PM;toto_UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;37484032;253118
07/15/19 02:55:59 PM;UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;37484032;253118
07/15/19 02:55:59 PM;UBV_FD_GSM_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;0;0

Needing 9 semicolons

I need 9 semicolons because it is possible that my last 2 data, per line, could be an error code and an error text. I do not have an example, but I need to insert null when I do not have an error code. So, is it possible to detect the number of semicolons per line, if 9 semicolons then the line is OK, if not add 2 semicolons at the end of the line. My first 7 data are mandatory, the last 2 are not. I can not load the file with a different number of separators in the lines of my file.

Then we need a fiddly second regex to provide the missing semicolons.  I'll also cater to the possibility of there being only the error code and not any error text.  This also handles data both with and without trailing spaces after the seven compulsory fields.
sed -e 's/ \{3,\}/;/g' \
    -e 's/^\([^;]*;\)\{1,8\}[^;][^;]*$/&;/' \
    -e 's/^\([^;]*;\)\{8\}$/&;/'

The second line is close to inscrutable, but \([^;]*;\)\{1,8\}[%;][%;]*$ can be split into a count (\{1,8\}) of 1 to 8 sequences of 'zero or more non-semicolons' ([^;]*), the body of a field, followed by a semicolon, all wrapped in grouping parentheses \(…\), and followed by one or more occurrences of something other than a semicolon and the end of line.  The replacement adds a semicolon.  This deals with lines without trailing spaces at the end, or those with one or two trailing spaces (three or more trailing spaces are converted to a semicolon by the first s///).
The last part looks for lines with 8 semi-colon terminated fields only, and adds an extra semicolon.
This is why I prefer to use -e options — it allows me to separate the complex regexes to make the code more readable (to the extent that regexes can be made readable).  You could combine all three -e options into a single string argument separated by semicolons:
sed 's/ \{3,\}/;/g; s/^\([^;]*;\)\{1,8\}[^;][%;]*$/&;/; s/^\([^;]*;\)\{8\}$/&;/'

but that is an intimidating command line to read.  You could omit the spaces; that makes it still harder to read.  I definitely prefer the clarity and readability of three separate -e options, not least because it is much, much, much easier to see the symmetry between the last two patterns when they're vertically aligned.
Fortunately, I test before posting.  For several iterations of the commentary and code above, the output data wasn't working as expected, in part because the data I had didn't have trailing spaces at the end.
Given this modified data (lines 2-4 have trailing blanks; line 1 doesn't; line 5 has an error code and error text; line 6 has an error code but no error text):
07/15/19 02:58:40 PM   toto2_UBD_FD_GPRS_GLBL_EXCP   TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            0
07/15/19 02:58:40 PM   toto_UBD_FD_GPRS_GLBL_EXCP    TABLE         DATA    COMPLETE   BASE_TEST_DSA   37484032     253118
07/15/19 02:55:59 PM   UBD_FD_GPRS_GLBL_EXCP         TABLE         DATA    COMPLETE   BASE_TEST_DSA   37484032     253118
07/15/19 02:55:59 PM   UBV_FD_GSM_GLBL_EXCP          TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            0
09/04/19 07:36:21 AM   UBV_FD_GSM_GLBL_EXCP          TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            252291   CORERROR   LIBERROR
09/04/19 07:36:57 AM   GRANLIBAKKEN                  CHAIR         DATA    COMPLETE   RUNCIBLE_SPOON   0            252291   CORERROR

For clarity, I have a program that adds \n after trailing white space.  It presents the data as:
07/15/19 02:58:40 PM   toto2_UBD_FD_GPRS_GLBL_EXCP   TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            0
07/15/19 02:58:40 PM   toto_UBD_FD_GPRS_GLBL_EXCP    TABLE         DATA    COMPLETE   BASE_TEST_DSA   37484032     253118      \n
07/15/19 02:55:59 PM   UBD_FD_GPRS_GLBL_EXCP         TABLE         DATA    COMPLETE   BASE_TEST_DSA   37484032     253118      \n
07/15/19 02:55:59 PM   UBV_FD_GSM_GLBL_EXCP          TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            0      \n
09/04/19 07:36:21 AM   UBV_FD_GSM_GLBL_EXCP          TABLE         DATA    COMPLETE   BASE_TEST_DSA   0            252291   CORERROR   LIBERROR
09/04/19 07:36:57 AM   GRANLIBAKKEN                  CHAIR         DATA    COMPLETE   RUNCIBLE_SPOON   0            252291   CORERROR   \n

The output from the sed script is:
07/15/19 02:58:40 PM;toto2_UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;0;0;;
07/15/19 02:58:40 PM;toto_UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;37484032;253118;;
07/15/19 02:55:59 PM;UBD_FD_GPRS_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;37484032;253118;;
07/15/19 02:55:59 PM;UBV_FD_GSM_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;0;0;;
09/04/19 07:36:21 AM;UBV_FD_GSM_GLBL_EXCP;TABLE;DATA;COMPLETE;BASE_TEST_DSA;0;252291;CORERROR;LIBERROR
09/04/19 07:36:57 AM;GRANLIBAKKEN;CHAIR;DATA;COMPLETE;RUNCIBLE_SPOON;0;252291;CORERROR;

I had the sed command in a simple file called chkit.sh, and one of the tests was:
$ sh chkit.sh < data | tr -dc ';\n'
;;;;;;;;;
;;;;;;;;;
;;;;;;;;;
;;;;;;;;;
;;;;;;;;;
;;;;;;;;;
$

The tr command deletes all characters except semicolon and newline, which allows me to see that the lines all have the same number of semicolons in them.  I also have a script length that prints the length of the line, a colon, a space and the content of the line:
$ sh chkit.sh < data | tr -dc ';\n' | length
9: ;;;;;;;;;
9: ;;;;;;;;;
9: ;;;;;;;;;
9: ;;;;;;;;;
9: ;;;;;;;;;
9: ;;;;;;;;;
$

So, the output always contains 9 semicolons.  This can be quite a useful way of validating delimited data as long as the delimiter does not appear within any of the data fields.
If I were working towards production code, the script would have a better name than chkit.sh and would have "$@" to take command line arguments (file names, or, indeed, extra script — I could add more -e '…' options to the command line; yet another reason to prefer using -e).
This also goes to show how crucial good (meaning comprehensive, covering all special cases as well as the routine) sample data is.  With different sample data, you might come up with a different solution.

A: $ awk -F'   ' -v OFS=';' '{$1=$1}1' file
07/15/19 02:58:40 PM;toto2;TABLE;DATA;COMPLETE;BASE_TEST;0;0;;
07/15/19 02:58:40 PM;toto;TABLE;DATA;COMPLETE;BASE_TEST;37484032;253118;;
07/15/19 02:55:59 PM;UBD;TABLE;DATA;COMPLETE;BASE_TEST;32;2;CORERROR;LIBLERROR
07/15/19 02:55:59 PM;UBV;TABLE;DATA;COMPLETE;BASE_TEST;0;0;;


text:
Q: Get multiple pixel coordinates by changing the width of a line drawn on an image? I am trying to create some image analysis code, I ask the user to draw a line or curve on an image, and the intensity of the pixels along this line is then recorded. I would like to be able to change the thickness of the line and take a mean of the pixels along the width to give an average of the intensity along each point of the line, I am unsure of how to do this. Visually I can change the thickness of the line on the plot, but it doesn't affect which/the number of pixels selected. I have included a sample of the code below.
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import sys

"""This class is a modification of the code created by Joerg Doepfert  2014 based on code posted by Daniel
Kornhauser. Which can be found at https://github.com/jdoepfert/roipoly.py /blob/master/roipoly.py """
class roipoly:
    def __init__(self, fig=[], ax=[], roicolor='b',thickness=2):
        if fig == []:
            fig = plt.gcf()
        if ax == []:
            ax = plt.gca()
        self.previous_point = []
        self.allxpoints = []
        self.allypoints = []
        self.start_point = []
        self.end_point = []
        self.line = None
        self.roicolor = roicolor
        self.thickness = thickness #I added this to change the thickness of the line on the plot
        self.fig = fig
        self.ax = ax
        self.__ID1 = self.fig.canvas.mpl_connect('motion_notify_event', self.__motion_notify_callback)
        self.__ID2 = self.fig.canvas.mpl_connect('button_press_event', self.__button_press_callback)
        if sys.flags.interactive:
            plt.show(block=False)
        else:
            plt.show()

    def displayIAL(self, **linekwargs):
        l = plt.Line2D(self.allxpoints,self.allypoints,color=self.roicolor,linewidth=self.thickness,**linekwargs)
        values=(self.allxpoints,self.allypoints)
        ax = plt.gca()
        ax.add_line(l)
        plt.draw()
        return values

    def __motion_notify_callback(self, event):
        if event.inaxes:
            ax = event.inaxes
            x, y = event.xdata, event.ydata
            if (event.button == None or event.button == 1) and self.line != None: # Move line around
                self.line.set_data([self.previous_point[0], x],[self.previous_point[1], y])
                self.fig.canvas.draw()

    def __button_press_callback(self, event):
        if event.inaxes:
            x, y = event.xdata, event.ydata
            ax = event.inaxes
            if event.button == 1 and event.dblclick == False:  # If you press the left button, single click
                if self.line == None: # if there is no line, create a line
                    self.line = plt.Line2D([x, x],[y, y],marker='o',color=self.roicolor, linewidth=self.thickness)
                    self.start_point = [x,y]
                    self.previous_point =  self.start_point
                    self.allxpoints=[x]
                    self.allypoints=[y]
                    ax.add_line(self.line)
                    self.fig.canvas.draw()
                    # add a segment
                else: # if there is a line, create a segment
                    self.line = plt.Line2D([self.previous_point[0], x],[self.previous_point[1], y],marker = 'o',color=self.roicolor,linewidth=self.thickness)
                    self.previous_point = [x,y]
                    self.allxpoints.append(x)
                    self.allypoints.append(y)
                    event.inaxes.add_line(self.line)
                    self.fig.canvas.draw()
            elif ((event.button == 1 and event.dblclick==True) or (event.button == 3 and event.dblclick==False)) and  self.line != None: # close the loop and disconnect
                self.fig.canvas.mpl_disconnect(self.__ID1) #joerg
                self.fig.canvas.mpl_disconnect(self.__ID2) #joerg
                self.line.set_data([self.previous_point[0],self.start_point[0]],[self.previous_point[1],self.start_point[1]])
                ax.add_line(self.line)
                self.fig.canvas.draw()
                self.line = None
                if sys.flags.interactive:
                    pass
                else:
                    #figure has to be closed so that code can continue
                    plt.close(self.fig)

#This function returns a list of lists with the x coordinates and the y coordinates being separated into their own lists
def getIAL(img, width):
    im = np.array(img)
    plt.imshow(im, interpolation='nearest', cmap="Greys")
    plt.title("left click: line segment, right click: close region")
    ROIl = roipoly(roicolor='g',thickness=width)
    plt.imshow(im, interpolation='nearest', cmap="Greys")
    myIAL=ROIl.displayIAL()
    plt.clf()
    return myIAL

#This function takes the intensity of each x,y coordinate and then plots     the intensities vs. distance along the line which was drawn
def IAL_Plot(IAL, image):
    xvalues=IAL[0]
    yvalues=IAL[1]
    imarray=np.array(image)
    intensityvalues=[]
    for i in range(len(xvalues)):
        x=int(xvalues[i])
        y=int(yvalues[i])
        intensityvalue=imarray[y,x]
        intensityvalues.append(intensityvalue)
    def display(Intensity):
        plt.plot(Intensity)
        plt.xlabel('Distance', fontsize=16)
        plt.ylabel('Intensity',fontsize=16)
        plt.show()
    display(intensityvalues)

#Generate a greyscale plot
array=np.linspace(0,1,256*256)
mat=np.reshape(array,(256,256))
img=Image.fromarray(np.uint8(mat*255),'L')

myIAL=getIAL(img, 5) #get the coordinates of a line drawn on the image
plot=IAL_Plot(myIAL,img) #get the intensity at each coordinate point

I would assume that there is either a pythonic way to do this or at least a mathematical way, but I am so far drawing a blank. Any help/advice would be much appreciated.


text:
Q: Create Git feature branch from another feature branch Is there a way in Git to create a Git feature branch (B) from another feature branch (A) but do not keep history from (A) and only display history of changes in B when create a PR?

A: To be able to do that, the commits in branch (A) would have to already be in the branch that you are performing the PR against.  Essentially branch (A) already needs to have a completed PR for it's commits, otherwise you will including commits from both branches in your PR.

A: If you're trying to create a PR into master, then you're going to have all the commits from A and B.
You can change B's base to master with the following command:
git rebase --onto master A B
The better solution is to just not branch off a feature branch if you don't really want the changes from that feature branch.


text:
Q: SQL condition on full name with no firstname/lastname order Given a column named fullname, how can I filter on firstname/lastname with no order ?
In the example below in javascript, the query is not valid when searching by lastname
function getQuery(searchWord){
  return `SELECT * FROM user WHERE fullname like '%${searchWord}%' `
}
// trying to search fullname "Elon Musk"
getQuery("Elon M") // okay
getQuery("Musk E") // no result

What is the query that allow me to find "Elon Musk" by searching by keyword "Musk Elon" ?
NB: columns firstname and lastname exists as well

A: You can do a FULLTEXT search using MATCH AGAINST:
SELECT * FROM user WHERE (MATCH (fullname) AGAINST ('${searchWord} IN NATURAL LANGUAGE MODE'))

And you have to create a FULLTEXT search index on the column fullname
Or you can split your searchWord by space and do LIKE '%$(searchWordPart1)%' AND LIKE '%$(searchWordPart2)%' etc.

A: Finally i resolved the problem by using some javascript.
  function getQuery(searchTerm = '') {
    // " Musk  E " => ["Musk", "E"]
    const arr = searchTerm.split(/\s+/).filter((e) => e)
    // ["Musk", "E"] => (first_name like '%Musk%' or  last_name like '%Musk%') AND (first_name like '%E%' or  last_name like '%E%')
    const conditions = arr
      .map((e) => `(first_name like '%${e}%' or  last_name like '%${e}%')`)
      .join(` AND `)
    return `use SNOW select distinct sys_id, name from dbo.sys_user where ${conditions}`
  }


text:
Q: Plotting array of vectors with conditions Given data in the form
list={{{1,2},{3,4},{5,6}},{{7,8},{9,10},{11,12}},...}

a matrix where elements are 2-element vectors, what is a efficient way to plot this as a spatial grid? As I understand
ArrayPlot[array,ColorFunction->(If[#>3,Red,White]&), ColorFunctionScaling->False]

can only be "fed" with normal array (no 2-vector like above), if you want to use Colorfunction If condition.
I want that a cell of the ArrayPlot mesh gets Red, when in {x,y} vector 1<x<2 AND y>3, otherwise White.
I know I could recreate the list into a {{1,0,1},{0,1,0},...} like normal array so ArrayPlot could read it, by using Table and Take, 1 and 0 representing the Red and White Case:
If[1<First[Flatten[Take[list,i]]]<2,1,0]

Then rebuild that list with Table and Join. But as far as I know MM, there has to be easier way, simply reading list and replacing a 2-vector with 1 or 0 1-vector under above conditions. Or do I really have to build the list completely new, problem is it has some million elements.
Thanks for any tips to improve this

A: It appears you have lied to us about ColorFunction, see:
ArrayPlot[RandomReal[{0, 1}, {10, 10, 3}]] (*this works, therefore...*)
ArrayPlot[RandomReal[{0, 1}, {10, 10, 3}], ColorFunction -> Hue]

These work, therefore:
ArrayPlot[RandomReal[{0, 3}, {10, 10, 2}],
 ColorFunction -> (If[1 < #[[1]] < 2 && #[[2]] < 3, Red, White] &)]

Beautiful. But if we go the extra mile, we can get:
ArrayPlot[RandomReal[{0, 3}, {10, 10, 2}],
 ColorFunctionScaling -> False,
 ColorFunction -> (If[1 < #[[1]] < 2 && #[[2]] < 3, Red, White] &)]

The default for ColorFunctionScaling /. Options[ArrayPlot] is True, which screws up your values. Compare the following to see the difference:
ArrayPlot[RandomReal[{0, 3}, {2, 2, 2}], ColorFunctionScaling -> True, ColorFunction -> Print]
ArrayPlot[RandomReal[{0, 3}, {2, 2, 2}], ColorFunctionScaling -> False, ColorFunction -> Print]

It makes sense in general since typical color functions such as Hue and ColorData[...] go from 0 to 1, but I've found you can often get more useful coloring by disabling the scaling.
$$-$$
Note: Apparently, ColorRules isn't affected by ColorFunctionScaling. This makes sense since ColorRules is typically used for integer data.
ArrayPlot[RandomReal[{0, 3}, {10, 10, 2}],
 ColorRules -> {{x_, y_} /; 1 < x < 3 && y < 3 -> Red, _ -> White}]

A: There are several ways to do this. Here are two that came to mind although I am sure there are many more
newArray1=Map[If[1 < #[[1]] < 2 && #[[2]] > 3, 1, 0] &, list, {2}]

newArray2=Replace[list, {{a_, b_} /; 1 < a < 3 && b > 3 :> 1, {a_, b_} :> 0}, {2}]

GraphicsRow[
    ArrayPlot[#, ColorFunction -> (If[# == 1, Red, White] &)] & /@ {newArray1,newArray2}
]


text:
Q: Escrever uma informação no console do browser através do .NET Preciso demonstrar informações no console no browser o clássico console.log do JavaScript, só que gostaria de fazer isto no browser com .Net e não no output do Visual Studio pois acredito que o Azure esteja impedindo a execução de alguns métodos de uma aplicação e como uma solução rápida pensei em inserir dentro dos métodos. Não sei se é possível, nem se é a melhor opção porem é uma resposta rápida.
Aplicação MVC4 , utilizo Firebug no browser.

A: Não é possível desta forma. O que roda no navegador é independente do que roda no servidor. Não tem como o servidor (no caso o ASP.NET) instruir diretamente o que o navegador deve executar.
O máximo que pode fazer é gerar uma página no C# (através de um view no MVC) que tenha um código em JavaScript  para ser executado pelo navegador (preferencialmente exista apenas a chamada ao JS nessa página e o código JS em si esteja em arquivo separado já definido e salvo de forma estática). Ou seja, o que importa para fazer isto é a parte que estará dentro do <script></script>.
Esta página obviamente será enviada ao servidor HTTP que posteriormente enviará ao navegador. O navegador que vai executar o código JS e fazer o que deseja.


text:
Q: Building i386 (32-bit) apps on x86_64 (64-bit) Mountain Lion I am building on a Mac OS X 10.8.2 workstation running GCC 4.7.2 obtained via MacPorts. I can build 64-bit (x86_64) apps with this setup.
I am trying to build a 32-bit binary from source by adding the -arch i386 to the compilation flags. I'd like to add support for 32-bit clients on 10.5 and 10.6.
I get the following error messages (among others) which seem relevant to the lack of 32-bit libraries:
ld: warning: ignoring file /opt/local/lib/gcc47/libgcc_ext.10.5.dylib, missing required architecture i386 in file /opt/local/lib/gcc47/libgcc_ext.10.5.dylib (1 slices)
ld: warning: ignoring file /opt/local/lib/gcc47/gcc/x86_64-apple-darwin12/4.7.2/libgcc.a, file was built for archive which is not the architecture being linked (i386): /opt/local/lib/gcc47/gcc/x86_64-apple-darwin12/4.7.2/libgcc.a

My questions are:

*

*Is there a different flag I should use for this, instead of -arch i386?

*Or, where can I obtain (or how can I compile) the i386 libraries I need to install, to get 32-bit support?
(Can I compile i386 architecture libraries from downloading GCC 4.7.2 source? Is there a specific set of options I should add to the ./configure statement to enable this?)

*

*Once these libraries are installed, how does my current gcc installation "know" where these libraries will be found?

*Is there anything I can add via Xcode 4.5.2? I am already doing this on the command-line, but I can only see "command-line tools" and iOS simulators as download options in the Preferences applet.

A: Remove the MacPorts install of GCC and install the "command-line tools" package through XCode. Once you've done this, gcc -arch i386 will work as expected.

A: Rebuilding the MacPorts installation of GCC 4.7.2 with the +universal option provided support for compiling both 32- (i386) and 64-bit (x86_64) binaries.


text:
Q: DIVs positions in gallery of images I'm creating a responsive skeleton of a gallery that will be inserted in a wordpress. The gallery is made of images of different sizes. The thing is I can't figure out how to stick div, which are on the "second row", right below the div of the "first row".
Here is a codepen of my actual work:
http://codepen.io/anon/pen/JdXPde
And I want my gallery to look like: http://webplantmedia.com/starter-themes/wordpresscanvas/features/gallery/gallery-columns/#gallery-6

A: Ahh, it loaded eventually. I don't think you can achieve what you are after with inline, inline-block nor floats. I think you would need to use absolute positioning as per what they are using on the link you forwarded. I can recommend using isotope https://github.com/metafizzy/isotope which does all that for you. It is a great tool.
Depending on your browser support matrix you could use CSS columns if you don't wish to use JS.
.wrapper {
    column-width: 500px;
    /* plus browser prefixes */
    -moz-column-width: 500px;
    -webkit-column-width: 500px;
}

Stick a div around your elements with a class of wrapper.


text:
Q: Dot Net Core Unit Testing using Xunit -> How to write initialization function for class I've started work on Unit Testing in Dot Net Core 2.0.
I've written a class to Unit Test controller class of my Web API.
Please find below the code of my Unit Test Class
public class ArticlesControllerTests
{
    private ArticlesController _articlesController;

    private Mock<IArticleRepository> _articleRepositoryMock = new Mock<IArticleRepository>();

    public ArticlesControllerTests()
    {
        _articlesController = new ArticlesController(_articleRepositoryMock.Object);
    }

    [ClassInitialize]
    public static void Init()
    {
        AutoMapperInit.Initialize();
    }
}

I want to write Init function that will call once and initialize AutoMapper configurations. But [ClassInitialize] is not there. I've searched online  but I was not able to find that attribute.
What should I do to make it work for Dot Net Core 2.0.

A: Using a static constructor on the test class should provide the same behavior
public class ArticlesControllerTests {
    private ArticlesController _articlesController;

    private Mock<IArticleRepository> _articleRepositoryMock = new Mock<IArticleRepository>();

    public ArticlesControllerTests() {
        _articlesController = new ArticlesController(_articleRepositoryMock.Object);
    }

    static ArticlesControllerTests() { //<-- static constructor
        AutoMapperInit.Initialize();
    }

    //...
}

the static constructor will call once and initialize AutoMapper configurations