text:
Q: spray-testkit with scalatest, status doesn't work I am trying to test a POST spray-route with scalatest which require a mandatory parameter adId. And Cannot make it work. My code follows
import akka.actor._
import akka.event.LoggingReceive
import akka.testkit.{TestProbe}
import com.ss.rg.service.ad.AdImporterServiceActor.{GetImportStatus, StatusOfImport}
import org.scalatest.{MustMatchers, WordSpecLike}
import spray.http.{StatusCodes, MediaTypes}
import spray.testkit.ScalatestRouteTest

class AdServiceApiTest extends  WordSpecLike with MustMatchers with ScalatestRouteTest{
 "AdService REST api " must{
   "POST for import witout mandatory parameters should fail with " in{
      val p = TestProbe()
      val addressServiceMock = system.actorOf(Props(classOf[AdServiceActorMock],p.ref))

      Post("/service/ad/import") ~> new AdServiceApi(addressServiceMock).route ~>check{
        handled must be(false)
        status must be (StatusCodes.BadRequest)
      }
    }
  }

The test fails but for a different reason
Request was rejected with List(MissingQueryParamRejection(adId))
org.scalatest.exceptions.TestFailedException: Request was rejected with List(MissingQueryParamRejection(adId))
    at spray.testkit.ScalatestInterface$class.failTest(ScalatestInterface.scala:25)
    at com.ss.rg.api.ad.AdServiceApiTest.failTest(AdServiceApiTest.scala:19)
    at spray.testkit.RouteResultComponent$RouteResult$$anonfun$response$1$$anonfun$apply$1.apply(RouteResultComponent.scala:97)
    at spray.testkit.RouteResultComponent$RouteResult$$anonfun$response$1$$anonfun$apply$1.apply(RouteResultComponent.scala:95)
    at scala.Option.foreach(Option.scala:236)
    at spray.testkit.RouteResultComponent$RouteResult$$anonfun$response$1.apply(RouteResultComponent.scala:94)
...

Seems that status hasn't been even checked.
Second thing which is not fully cleared to me is how to actually set a adId parameter in spray-testkit? One way would be via setting the header but I wouldn't be surprised that a better way would exist.
Can somebody more experienced with spray-testkit comment?
Thx

A: There isn't a status - the route rejected the request. You can access the rejection as rejection and assert that it's the type you expect. If you want to check what the browser would actually see you should wrap the route in a handleRejections directive using the default RejectionHandler (it's available implicitly) and then you'll be able to see the status code you'd expect. In that case handled will come out as true though (because the wrapped route will handle the request - by returning a response with a failed statuscode and an error message).


text:
Q: When to use "make" versus when to use "do" I have trouble choosing between make and do in a sentence. Could someone please explain them to me?

A: As a native speaker of English (no linguist), I can give a simple answer:

*

*"Make" usually denotes creation of a "new" product or result.
Examples: Mother will make dinner. The accident made a lot of noise. Don't make me angry!
Exceptions seem to be in informal uses of "make": How did you make out? (This usage means to ask about the quality of one's experience or level of success.) He's on the make. (This is an idiomatic usage)

*"Do" is used to denote engagement in a specific task; the product or result (if any) is less important than engagement in the task.
Examples: The student must do the homework. My husband hates to do laundry. I have nothing to do this evening.
Informal usages: The killer did him in with an ax (murdered). He wants to do her (have intercourse).
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: .htaccess drupal 7 RedirectMatch or RewriteRule nothing seams to work I'm having some real issues getting a redirect to work in .htaccess with drupal 7.
I have links like this:
example.com/vid/category/filter?subcat_filter_depth=125

and I need them to go to: (on same domain)
example.com/vid/category/filter?type=All&subcat_filter_depth=125

after = the number may be different like 67 or 32 etc. meaning that can be any number and whatever number is at the end of the original link needs to also be at the end of the new link.
I think the fact that the link is pretty much the same path just different filter is what is causing the issue as even the Drupal redirect url module will not allow it at an attempt to add them one at a time as they occur.
here is everything I've tried:
RedirectMatch 301 ^/vid/category/filter?subcat_filter_depth=(.*) /vid/category/filter?type=All&subcat_filter_depth=$1

RewriteRule ^(.*)/vid/category/filter?subcat_filter_depth=(.*) $1/vid/category/filter?type=All&subcat_filter_depth=$2 [R=301]

RedirectMatch ^/vid/category/filter?subcat_filter_depth=(.*) ^/vid/category/filter?type=All&subcat_filter_depth=$1

RedirectMatch 301 ^(.*)/filter?subcat_filter_depth=(.*) ^$1/filter?type=All&subcat_filter_depth=$2

RedirectMatch ^/(.*)/filter?subcat_filter_depth=(.*) ^/$1/filter?type=All&subcat_filter_depth=$2

RewriteRule "^/(.*)/filter?subcat_filter_depth=(.*)" "^/$1/filter?type=All&subcat_filter_depth=$2"

mod_rewrite is on and there is an AllowOverride pathed/to/the/.htaccess file under <Directory> inside <VirtualHost> in the 000-default.conf running on Debian Apache ..pretty much latest versions.
I know mod_rewrite is working because if I add a bad rule or rewrite with a syntax error I get error 500 response page.
I've searched and tried just about everything I can think of and nothing seems to work.
Any help getting this sorted and functioning would be greatly appreciated!

A: Both the RedirectMatch (mod_alias) and RewriteRule (mod_rewrite) directives match against the URL-path only, which notably excludes the query string.
To match against the query string you need to use RewriteRule with an additional condition (RewriteCond directive) that checks against the QUERY_STRING server variable.
This rule also needs to go near the top of the .htaccess file, before any existing rewrites.
For example:
RewriteCond %{QUERY_STRING} ^subcat_filter_depth=\d+$
RewriteRule ^vid/category/filter$ /$0?type=All [QSA,R=302,L]

This redirects example.com/vid/category/filter?subcat_filter_depth=<number> to example.com/vid/category/filter?type=All&subcat_filter_depth=<number>.
In .htaccess there is no slash prefix on the URL-path matched by the RewriteRule pattern. ie. ^vid/category (not ^/vid/category).
$0 is a backreference that contains the matched URL-path from the RewriteRule pattern.
QSA causes the original query string (eg. subcat_filter_depth=125) to be appended to the query string stated in the substitution string, ie. type=All becomes type=All&subcat_filter_depth=125.
Test with 302 (temporary) redirect to avoid potential caching issues. Only change to a 301 (permanent) redirect - if that is the intention - once you have confirmed it works as intended.
You will likely need to clear your browser cache before testing.

A: I was able to come up with a solution that worked prior to the answer (above) I marked as correct as my solution isn't quite as elegant.

*

*I did realize after a bit of more research I needed to use a RewriteCond with %{QUERY_STRING} for what I was trying to achieve.

*Again not as elegant as the answer above...but here is my code:
RewriteCond %{REQUEST_URI} ^/vid/category/filter [NC]
RewriteCond %{QUERY_STRING} ^(.*)=(.*)
RewriteRule (.*) /vid/category/filter?type=All&subcat_filter_depth=%2 [R=301,L]

This actual kept the url in the browser as it was input (/var/category/filter?subcat_filter_depth=) but showed the page as if it was opened with the proper filter for type=ALL and produced no errors both in browser and in Drupal dblog.
The above solution is more useful in explanation alone and gave me much better understanding of how to break up a URL and put it back together with modifications especially when dealing with strings that have variables that change like unique ID's.


text:
Q: Strange issue with useQuery: Query arguments not being read I have a component that passes a string (userToFetch) it as a variable parameter in a parameterized query. The component looks like this:
// pages/index.jsx

import React from 'react';
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';

const GET_USERS = gql`
  query users ($limit: Int!, $username: String!) {
    users (limit: $limit, where: { username: $username }) {
      username
      firstName
    }
  }
`;

const Home = () => {
  const userToFetch = 'jonsnow';

  const {
    loading,
    error,
    data,
  } = useQuery(
    GET_USERS,
    {
      variables: { limit: 2, username: userToFetch },
      notifyOnNetworkStatusChange: true,
    },
  );

  if (loading) {
    return
Loading...
;
  }

  if (error) {
    return
Error: {JSON.stringify(error)}
;
  }
  return (

        {data.users.map(user => {
          return
{user.username} {user.firstName}
;
        })}

  );
};

export default Home;

And this is how I have configured my Apollo client:
// /apollo-client.js

import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import withApollo from 'next-with-apollo';
import { createHttpLink } from 'apollo-link-http';
import fetch from 'isomorphic-unfetch';

const GRAPHQL_URL = 'https://dev.schandillia.com/graphql';

const link = createHttpLink({
  fetch, // Switches between unfetch & node-fetch for client & server.
  uri: GRAPHQL_URL
});

// Export a HOC from next-with-apollo
// Docs: https://www.npmjs.com/package/next-with-apollo
export default withApollo(
  // You can get headers and ctx (context) from the callback params
  // e.g. ({ headers, ctx, initialState })
  ({ initialState, ctx }) => {
    console.log('initialState', initialState);
    console.log('ctx', ctx);

    return new ApolloClient({
      link: link,
      cache: new InMemoryCache()
        //  rehydrate the cache using the initial data passed from the server:
        .restore(initialState || {})
    })
  }
);

The database is a collection of following users:
"users": [
      {
        "username": "negger",
        "firstName": "Arnold",
        "lastName": "Schwarzenegger"
      },
      {
        "username": "jonsnow",
        "firstName": "Jon",
        "lastName": "Snow"
      },
      {
        "username": "tonystark",
        "firstName": "Tony",
        "lastName": "Stark"
      }
    ]
  }

Now, although this should work (it does when I run the query in my graphql playground at https://dev.schandillia.com/graphql), the code runs as if the where clause didn't exist! It just returns all results as if the query being run were:
users {
  _id
  username
  firstName
}

In order to reproduce the issue, visit https://www.schandillia.com. The page ought to display a list with only one element consisting of a matching username-firstName value: jonsnow Jon but it returns two entries, negger Arnold and jonsnow Jon (respecing limit but completely ignoring where). Now, run the same query with jonsnow as a where parameter in https://dev.schandillia.com/graphql:
{
  users(where: { username: "jonsnow" }) {
    _id
    username
    firstName
  }
}

And the results would be exactly as expected:
{
  "data": {
    "users": [
      {
        "_id": "5d9f261678a32159e61018fc",
        "username": "jonsnow",
        "firstName": "Jon",
      }
    ]
  }
}

What am I overlooking?
P.S.: The repo is up for reference at https://github.com/amitschandillia/proost/tree/master/apollo-nextjs.
UPDATE: In order to track down the root cause, I tried logging some values in apollo-client.js:
console.log('initialState', initialState);

Strangely, the output shows the right query, along with the variables being passed, but wrong results:
...
ROOT_QUERY.users({"limit":2,"where":{"username":"jonsnow"}}).0:
  firstName: "Arnold"
  username: "negger"
  __typename: "UsersPermissionsUser"
...

UPDATE: Here's a screenshot of results in my Apollo Client Developer Tools:

A: The schema generated by Strapi gives the where attribute a Type JSON and hence you have to pass the entire where part in the query variable as JSON since the variables are not getting injected.
# Write your query or mutation here
query users($where: JSON) {
  users(where: $where) {
    username
    firstName
  }
}

And the variables would look like:
{"where": {"username": "jonsnow"}}


text:
Q: nonlinear least-square with Python statsmodels Within the Python library statsmodels, is it possible to perform a nonlinear least-square fitting with nonlinear parameter? In other words, I would like to find the best fit (in term of least-square) for p in the following stat model:
y = ln(p)*x^2 + p
Let's assume I have a set of observation x and y, I can use the function scipy.optimize.leastsq to find the best fit. Here is an example:
import numpy as np
import scipy.optimize as spopt
import matplotlib.pyplot as plt

def fitFunc(p,x):
    return np.log(p[0])*x**2 + p[0]
def errFunc(p,x,y):
    return fitFunc(p,x)-y

# create x, y and y_true
nSample = 100
x = np.linspace(-10,10,nSample)
y_true = fitFunc([1.2],x)
err = np.random.normal(scale=7.0,size=nSample)
y = y_true+err

# find optimal p with least-square and plot it
p1, success = spopt.leastsq(errFunc, [2], args=(x,y))

plt.figure()
plt.scatter(x,y,label='obsevation')
plt.plot(x,y_true,label='true y')
plt.plot(x,fitFunc(p1,x),label='model')
plt.grid(True)
plt.legend()

Is it possible to perform such type of analysis with the library statsmodels?


text:
Q: Console : background color fills line when exceeding buffer I was printing alot to the windows-console in different colors for testing, and setting the text and backgroundcolor at random. When the lines exceed the console-buffer, the background color is set to the entire line. Here is an example in C#:
static void Main( String[] args )
{
    Console.BufferHeight = 16;

    foreach( var i in Enumerable.Range( 0 , Console.BufferHeight + 3 ) )
    {
        var fgColor = Console.ForegroundColor;
        var bgColor = Console.BackgroundColor;
        var tst = i % 2 == 0;
        Console.ForegroundColor = tst ? ConsoleColor.White : ConsoleColor.Black;
        Console.BackgroundColor = tst ? ConsoleColor.Black : ConsoleColor.Yellow;
        Console.WriteLine( $"{i} HELLO WORLD" );
        Console.ForegroundColor = fgColor;
        Console.BackgroundColor = bgColor;
    }

    Console.ReadLine();
}

I already set the buffer to its max buffer size (16 bit), but this application will print several million lines in the future.
Is there a fix for that?

A:
I already set the buffer to its max buffer size (16 bit), but this application will print several million lines in the future.

Then I think you mean Int16.MaxValue instead of 16.
Anyway, to fix your issue, just restore the color before writing the end of line character:
foreach (var i in Enumerable.Range(0, Console.BufferHeight + 3))
{
    var fgColor = Console.ForegroundColor;
    var bgColor = Console.BackgroundColor;
    var tst = i % 2 == 0;
    Console.ForegroundColor = tst ? ConsoleColor.White : ConsoleColor.Black;
    Console.BackgroundColor = tst ? ConsoleColor.Black : ConsoleColor.Yellow;
    Console.Write($"{i} HELLO WORLD");
    Console.ForegroundColor = fgColor;
    Console.BackgroundColor = bgColor;
    Console.WriteLine();
}


text:
Q: onmouseover opacity change isn't working Any idea why this isn't working? The default style in CSS is opacity = 0. Not only does the opacity not change in the div I want to appear, but when the mouse goes over the link it doesn't even show it as being a link. (it works well when I use "visibility" instead of the opacity property, but it causes blinking due to the action triggering the "onmouseout" event)
<a href="#" onMouseOver=" document.getElementById('pop_up1').style.opacity = 1" onMouseOut="document.getElementById('pop_up1').style.opacity = 0">

Here's the CSS:
#pop_up1 {
    opacity: 0;
    position:fixed;
    width: 100%;
    height: 100%;
    z-index: 2;
    text-align: center;
}

Oh wait, I think I see the problem. Even though the #pop_up1 div is invisible it is still over all the links and thus nothing is registered by the mouse at all. Is there a way to solve this problem?

A:
"Oh wait, I think I see the problem. Even though the #pop_up1 div is
  invisible it is still over all the links and thus nothing is
  registered by the mouse at all. Is there a way to solve this problem?"

-- use display:none instead of opacity to hide it, like
#pop_up1 {
    display:none;
    position:fixed;
    width: 100%;
    height: 100%;
    z-index: 2;
    text-align: center;
}


text:
Q: mongo db pull element out of an array I have a small mongo document which looks like this:
{
    "_id": {
        "$oid": "5aa441e898cc0b32a819be0c"
    },
    "details": {
        "Artist": "Cyndi Lauper",
        "Album": "She's So Unusual",
        "ReleaseYear": 1983
    },
    "SongID": 1,
    "SongTitle": "Girls Just Want To Have Fund"
}

I need to pull the Artist element out of the details array but keep the data in the overall document.  The resulting document needs to look like this:
{
    "_id": {
        "$oid": "5aa441e898cc0b32a819be0c"
    },
    "details": {
        "Album": "She's So Unusual",
        "ReleaseYear": 1983
    },
    "SongID": 1,
    "SongTitle": "Girls Just Want To Have Fund",
    "Artist": "Cyndi Lauper"
}

I'm new to mongo so I'm not to strong in this. The collection is called songs so am thinking I need to do something like this:
db.songs.updateOne({},{$set : {"Artist":$pull{"detail.Artist"}}})

Any help and/or suggestions are greatly appreciated.
Jonathan

A: You can write something like this in the MongoDB shell:
var doc={doc:{key42:"value"},somekey:"value"};
doc.key42=doc.doc.key42;
delete doc.doc.key42;

After that you can write
doc

and press enter.
The output shold be:
{doc:{},somekey:"value",key42:"value"};

Then you can save the doc:
db.collection.save(doc);


text:
Q: How to let a user choose the hex color for an embed command? | Discord.py I am making a embed/say command for my bot and I am unsure how to let the user choose the embed color by entering a hex color.
I have tried this:
@client.command(aliases=['say'])
@commands.has_permissions(manage_messages=True)
async def embed(ctx):

    questions = ["Which should be the tile of the embed?",
            "What should be the description?",
            "What is the color of the embed? This should be a hex color."]

    answers = []

    def check(m):
        return m.author == ctx.author and m.channel == ctx.channel

    for i in questions:
        await ctx.send(i)

        try:
            msg = await client.wait_for('message', timeout=30.0, check=check)
        except asyncio.TimeoutError:
            await ctx.send('You did not answer in time. Please do it under 30 seconds next time.')
            return
        else:
            answers.append(msg.content)

    embedcolor = answers2[2]

    embed = discord.Embed(description=answers[1], title=answers[0], colour=0x(embedcolor))

    await ctx.send(embed=embed)

And I get this error: SyntaxError: invalid hexadecimal literal
I have also tried letting the user input the hex color with the 0x in front of it to no success. I have also tried turning this user input into an integer with no success.
Thanks for the help!

A: Yes, it's an invalid format, you're doing something like so
>>> 0x"ff0000"
SyntaxError: Invalid hexadecimal literal

If you want to convert a string to a hex integer
>>> int("ff0000", 16)
16711680

embed = discord.Embed(..., colour=int(embedcolor, 16))


text:
Q: Move the variables pane in Pycharm's Python Console When debugging in PyCharm, I can move the Variables pane by dragging it, like so:

to

Using the latter layout (the vertical one) is very useful for me, especially in Float/Window view mode, as I'm debugging on a second screen which is rotated 90 degrees.
But when I'm using the Python Console for experimenting (e.g. running the code in Scientific Mode), I can't seem to find a way of moving the variables part from the horizontal (side by side) layout to a vertical one. The only thing I can do is resizing by dragging the separator between the console output and the variables.

I'm aware of the possibility that the variables part of the Python Console is 'not the same type' as the Variables pane in the Debug window. But still, is there no way of moving the variables part below the console output? I'm using PyCharm Professional 2019.1 on Ubuntu 16.04.


text:
Q: Function to turn text into voice while using skype or similar on iPhone so ideally I would like to type and turn the text into voice that speaks to the person on the other end of skype, on my iphone, is there something like that? Doesn't have to be skype if there is another app that can phone and do this type-to-voice function simultaneously.

A: A cursory search of the App Store reveals iSpeech, which is basic and doesn't have the greatest reviews, but looks like it will suffice. There are many more applications available simply search "text to speech" on the App Store.


text:
Q: Sharepoint 2010 extremely slow. Please advise Our SharePoint site is going extremely slow, especially when trying to delete items - majority (90%) of triggered Workflows fail and give Error Occurred -  Editing or adding data is a nightmare.
What could be causing the issue ? Any troubleshooting steps to follow ?
Our memory usage is between 70 and 80% and won't lower even if we stopped loading or editing large volume of data.
Is there a possibility to figure out where the traffic is coming from ( Site/ crazy Workflows)?
We have around 30 Lists ( contain average of 15000 items each).

A: There are couple of things you can check.

*

*Check the ULS logs and see on which operation it is spending too much. Here is good article, how to do performance filter in ULS logs.

*You can also check the space on the SQL server, Performance of Memory and CPU

*sometime, it is  simply the server's are overloaded and hardware not meet the capacity requirement. You may need add more memory.

*Check the IIS logs to examine the traffic

*Enable the Caching, sometime help the performance issue.

*Check your List view threshold, if it more than 5K then it can cause the performance issue

*Check the Workflow history list, sometime this contains millions of data which cause the performance issue

*Also avoid the large insertion / deletion / editing operations during the peak hours.

A: I concur with Waqas on the pointers he provided, however, in my 15 years in troubleshooting SharePoint performance problems, nine out of ten times it ends up being SQL server. You mentioned you're doing mass data loads. I would start by checking the Auto Grow settings on your Content Database in SQL Server. By default SharePoint sets this to 1MB. This is orders of magnitude too small for SharePoint. Even if you modify your Model database to have increased settings, SharePoint still ignores that and uses 1MB. I recommend changing that to 1GB. This will reduce the number of auto grows that SQL had to do this improving SharePoint performance. Probably the best first step is to pull a list of heavy queries in SQL. From there you'll be able too see if a particular list is a common culprit and then look at the statements to find fields that could use indexes to improve performance.


text:
Q: I can't find any grammatical errors

I think it's correct grammar, but where is it wrong?

A: I don't have enough reputation to write a comment so I just write my finding here.
You are missing a close bracket in the line history = model.fit_generator(...)
, the line before the return statement

A: You forgot to add a closing bracket after defining history.
history = model.fit_generator(
    The parameters you added )
                             ^ You had forgotten to add this

This is why Python considered the return statement invalid


text:
Q: Dynamic rows to columns from multiple tables with mysql So I've been reading through some of the other questions about dynamic rows to columns. By adapting another query in another answer here
mysql select dynamic row values as column names, another column as value,
I can get it to work for a single table, however I need to also pull records from two other tables to include in the result. Given these tables:
Cars
ID    BRAND    NAME   etc1...
1     gmc      sierra
2     ford     ranger
3     dodge    dakota
4     kia      rio

Dice
ID    DESCRIPTION
1     blue
2     green
3     red
etc2. etc2.

Stock
ID    CAR_ID    DICE_ID    NUMBER
1     1         3          01V,3Y6
2     3         1          8Z4
3     2         2          03X
4     1         1          C7B

So yes this doesn't make much sense but it's only to show the structure. My result needs to come out looking like this:
CAR_ID    BRAND    NAME    etc1.    BLUE    GREEN    RED     etc2.
1         gmc      sierra  ...     C7B     null     01V,3Y6 ...
2         ford     ranger  ...     null    03X      null    ...
3         dodge    dakota  ...     8Z4     null     null    ...
4         kia      rio     ...     null    null     null    ...

Simple if it was static but the number of rows in Cars and Dice will be dynamic so it can't be hard-coded. I can get Dice to output the rows into columns but there are two things I can't figure out:

*

*The main query is supposed to list all columns from the Cars table along with all rows as columns from the Dice table but I can't figure out how to attach the Dice query to the Cars query.

*I need to pull the relative description from the Dice table to use as a column header. Using dice.id is not practical or helpful. I can't figure out how to incorporate this into my working query for the Dice table.

Does anyone know how to produce the desired results?
Edit 1: I forgot to say that the results must list ALL Cars whether or not they have Dice in stock.
Edit 2: I should have clarified that NUMBER meant product number and not count. This is a string field that can hold multiple product numbers. It's legacy data.

A: Try this:
SET SESSION group_concat_max_len = 10000;
SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(D.ID = ',D.ID,', D.ID, NULL)) as \'', D.DESCRIPTION, '\'')) INTO @sql FROM Dice D;

SET @s = CONCAT('SELECT C.*, ', @sql, ' FROM Cars C INNER JOIN Stock S ON C.Id = S.Car_Id  INNER JOIN Dice D ON S.DICE_ID = D.ID GROUP BY C.ID');

PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;


text:
Q: Hibernate_sequence does not exist with hibernate envers I am using Hibernate Envers with entity
@Entity
@Table(name = "users", schema = "core")
@Audited public class Users implements java.io.Serializable, Comparable<Users> {
    protected static final long serialVersionUID = 1250157348010696249L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "userid")
    protected Integer userId;

    @Column(name = "aduserid")
    protected String aduserId;

    @Column(name = "firstname")
    protected String firstName;

    @Column(name = "middlename")

i am getting error hibernate sequence does not exist .
when i am changing false
then it says revision generator does not exist.
Pls help me.

A: Hibernate Envers expects a global sequence "hibernate_sequence" in order to insert into the "revinfo" table.

A: you need to create hibernate_sequence in your database,
check sample code
CREATE SEQUENCE hibernate_sequence  INCREMENT 1  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 1
  CACHE 1;


text:
Q: Error in SPRING JPA using eclipse link POSTGRESQL when executing findBy[NAME]In(List ids) I got a problem with my SPRING JpaRepository class when trying to use the findByIdIn(List ids), eg i want to pass a list of ids to the native query and expect it to return a list of objects.
Maven dep.:

*

*spring-data-jpa 1.4.2

*org.eclipse.persistence.jpa 2.5.1

DB:

*

*PostgreSQL 9.3

Appserver:

*

*Glassfish 4.0

Here is my repository class
@Repository
public interface TransactionRepository extends JpaRepository<Transaction, Long>, QueryDslPredicateExecutor<Transaction> {

    List<Transaction> findByIdIn(List<Long> ids);
}

Field id in database is BIGINT.
When I pass ONLY 1 object in the list it works, when it's 0 or more than 1 object in the list I receive this error:
Local Exception Stack:

Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.1.v20130918-f2b9fc5): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: operator does not exist: bigint = record
  Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
  Position: 160
Error Code: 0
Call: SELECT ID, amount, comment, created_date, currency, status, transaction_step, transaction_type, version, provider_id, user_id FROM anix.transactions WHERE (ID IN ((?,?)))
    bind => [2, 3]
Query: ReadAllQuery(referenceClass=Transaction sql="SELECT ID, amount, comment, created_date, currency, status, transaction_step, transaction_type, version, provider_id, user_id FROM anix.transactions WHERE (ID IN (?))")
    at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:340)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:682)
    at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:558)

The SQL works fine in my admin tool if I copy/paste it there.
--- EDIT ---
@Entity
@Table(name = "transactions", schema = "anix")
@XmlRootElement
@XmlAccessorType(FIELD)
public class Transaction implements Serializable {
    @Id
    @SequenceGenerator(name = "transactions_sequence", sequenceName = "transactions_id_seq", initialValue = 1, allocationSize = 1)
    @GeneratedValue(strategy = SEQUENCE, generator = "transactions_sequence")
    @XmlID
    @XmlElement
private Long id;

Would appreciate any help on this!
Regards

A: Looks like a BUG. See here: DATAJPA-433 and here: Bug 349477


text:
Q: How can i pass a variable with url in javascript code? I want to pass a variable with URL in JavaScript code. Variable comes from database. I see many answer in StackOverflow. But I think, I don't find any right answer for my problem. Code are given bellow:
This code is in my index page.

This code is in code.js file.
// JavaScript Document

$(document).ready(function(){

/* Data Insert Starts Here */
$(document).on('submit', '#emp-SaveForm', function() {

   $.post("video_create.php?lang=$lang", $(this).serialize())
    .done(function(data){
        $("#dis").fadeOut();
        $("#dis").fadeIn('slow', function(){
             $("#dis").html('
'+data+'
');
             $("#emp-SaveForm")[0].reset();
         });
     });
     return false;
});
/* Data Insert Ends Here */

/* Data Delete Starts Here */
$(".delete-link").click(function()
{
    var id = $(this).attr("id");
    var del_id = id;
    var parent = $(this).parent("td").parent("tr");
    if(confirm('Sure to Delete ID no = ' +del_id))
    {
        $.post('video_delete.php?lang=$lang', {'del_id':del_id}, function(data)
        {
            parent.fadeOut('slow');
        });
    }
    return false;
});
/* Data Delete Ends Here */

/* Get Edit ID  */
$(".edit-link").click(function()
{
    var id = $(this).attr("id");
    var edit_id = id;
    if(confirm('Sure to Edit ID no = ' +edit_id))
    {
        $(".content-loader").fadeOut('slow', function()
         {
            $(".content-loader").fadeIn('slow');
            $(".content-loader").load('video_edit.php?edit_id='+edit_id);
            $("#btn-add").hide();
            $("#btn-view").show();
        });
    }
    return false;
});
/* Get Edit ID  */

/* Update Record  */
$(document).on('submit', '#emp-UpdateForm', function() {

   $.post("video_update.php?lang=$lang", $(this).serialize())
    .done(function(data){
        $("#dis").fadeOut();
        $("#dis").fadeIn('slow', function(){
             $("#dis").html('
'+data+'
');
             $("#emp-UpdateForm")[0].reset();
             $("body").fadeOut('slow', function()
             {
                $("body").fadeOut('slow');
                window.location.href="video.php?lang=$lang";
             });
         });
    });
    return false;
});
/* Update Record  */
});

All URL pass a variable

lang=$lang

. $lang is en or bn but it comes from database table. How can i make it usable?

A: you can set javascript array on your index page like that.
Note : Put this script before include your code.js file

Now in your code.js file
'video_delete.php?lang='+global_var.lang

A: If you are want to pass data to url and you are not using inline JS then you can declare global variable and then use it in *.js file.
Ex:
This code is in my index page.

This code is in code.js file.
 // js code
 $.post("video_update.php?lang="+$lang, $(this).serialize())
 // Js code


text:
Q: Unusual android activity lifecycle I wrote a game, and in logs from market i sometimes see following pattern:
06:02:13:835|INFO|1|MainActivity|MainActivity#2.OnCreate
06:02:13:932|INFO|1|MainActivity|MainActivity#2.OnStart
06:02:14:010|INFO|1|MainActivity|MainActivity#2.OnResume
...
06:09:27:688|INFO|1|MainActivity|MainActivity#2.OnPause
06:09:28:895|INFO|1|MainActivity|MainActivity#3.OnCreate
06:09:29:159|INFO|1|MainActivity|MainActivity#3.OnStart
06:09:29:319|INFO|1|MainActivity|MainActivity#3.OnResume
06:09:29:551|INFO|1|MainActivity|MainActivity#2.OnStop
06:09:29:596|INFO|1|MainActivity|MainActivity#2.OnDestroy

MainActivity instance #3 is created and started before MainActivity instance #2 is destroyed. What does this pattern mean ? Why does new instance start before previous has been destroyed ?
Obviously i don't create activity by hand. Users simply start game by tapping icon(at least i hope so).
Activity has singleTask launch mode.
Thank you!

A: The onDestroy callback is not guaranteed to be called. From the docs:

onDestroy() = The final call you receive before your activity is
  destroyed. This can happen either because the activity is finishing
  (someone called finish() on it, or because the system is temporarily
  destroying this instance of the activity to save space. You can
  distinguish between these two scenarios with the isFinishing() method.

A: Suppose your application has two activities. Then this would be the life cycle

onDestroy will be called if you explicitly call finish(); yourself or like the example if you press Back button because pressing back key actually provokes finish() method on your activity, and it causes your activity to be paused->stopped->destroyed


text:
Q: How to convert interest rate to discount factor I'm studying on Kellison's Theory of Interest and I'm stuck on the exercise 20/a of the 1st chapter.
If the $i=0.1$ then $d = 0.0901$
$d_5=\frac{A_5-A_4}{A_5}$
when I insert $d$ into this equation, I reach to the;
$\frac{  (1/(1-5d))  -  (1/(1-4d))}{1 / (1-5d) }$ which is simplified as $\frac d{1-4d}$.
When I put the $0.0901$ value for $d$, I can't reach to the answer of $\frac1{15}$ with this solution.
But if I insert $i$ instead of $d$, I reach to $\frac i{1+5i}$ then the result is $\frac1{15}$, which is correct.
After this non-resulting work, I wanted to see the cash flow of this example. And I made  a table in excel with $A_0=100$, $i = 0.1$  and $d= 0.0901$. And surprise surprise I couldn't find the same cash flow by using $i$ and $d$. At the 5th period, the simple interest accumulated value is 150, while the one with simple discount is $183.33$ (with the formula $\frac A {1 - nd}$). Actually, after the first period, the cash flow with the discount rate started to get higher than the one with the interest rate.
As a result I really don't understand how $i$ is converted into $d$.
Any help?
Note: Sorry for the messy equation syntax, I don't how to do it here properly.

A: You are assuming the formula $d = \frac{i}{i+1}$ for simple interest when that formula is only valid for compound interest.  Thus, your first step of determining $d = 0.0901$ is incorrect.
To answer your second question, asked in the comment, if $i$ and $d$ are equivalent rates of simple discount, then $1 + it = \frac{1}{1 - dt}$, so just solve for one or the other.  Note, however, that the accumulation function for simple discount is only defined for $0 \leq t < \frac{1}{d}$, so they can only be equivalent over this interval.
We have
$$1 = (1 + it)(1 - dt) = 1 - dt + it - idt^2.$$
Subtracting one from both sides gives
$$-dt + it - idt^2 = 0.$$
Of course, this holds true when $t = 0$, so let's assume $t \neq 0$ and that allows us to divide both sides by $t$.  This gives
$$i - d = idt.$$
You can solve this for $i$ or $d$ easily now.  Note that a constant simple interest rate $i$ will NOT lead to a constant discount rate $d$, which is clear because there is still a $t$ left in our equation.  And, similarly, a constant simple discount rate will not lead to a constant simple interest rate.  These facts are clear even before we solve this because $1 + it$ is linear when $i$ is constant and $\frac{1}{1 - dt}$ is not linear when $d$ is constant.


text:
Q: Makes all html links clickable when displaying a NSAttributedString in UITextView I want to display some HTML that contains links ( tag) in a UITextView, and makes those links clickable.
For that I use a NSAttributedString initialized with the HTML data and the appropriate options for HTML.
NSString* html =   @""
                    ""
                    ""
                    "<base href='http://en.wikipedia.com' target='_self'>"
                    ""
                    ""
                    "link"
                    "link"
                    ""
                    "";

NSAttributedString* attStr = [[NSAttributedString alloc] initWithData:[html dataUsingEncoding:NSUnicodeStringEncoding]
                                                              options:@{
                                                                        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                                                        NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
                                                                       }
                                                   documentAttributes:nil
                                                                error:nil];

In the html string, you can see two  links with href attributes referring to:

*

*The stack overflow URL for the first one.

*A URL with only the fragment part for the second one. (https://developer.apple.com/reference/foundation/nsurl)

Next, I set the attributed text in the UITextView
_textView.attributedText = attStr;

When executing, all is well displayed in the view, but only the stackoverflow link is clickable. I want to be able to make the other one clickable too. It seems that NSAttributedString does not make all html links clickable, but only those with valid URLs.
Any ideas how I could do that using NSAttributedString?
Thanks!


text:
Q: Looping through a specific group of text box Hi I have seen basics of looping however, when looping through specific checkboxes, what would I add within the jquery code besides the basic loop function below? Like what can I use to loop through a group of checkboxes specially.  thank you. I added the HTML format of checkboxes below.
$( "A" ).each(function( index ) {
  console.log( index + ": " + $( this ).text() );
});

            A-1
                <input type="checkbox" value="A1" name="A1" id="A1" tabindex="1" class="A">

            A-4
               <input type="checkbox" value="A4" name="A4" id="A4" tabindex="4" class="A">

          A-2
              <input type="checkbox" value="A2" name="A2" id="A2" tabindex="2" class="A">

          A-5
              <input type="checkbox" value="A5" name="A5" id="A5" tabindex="5" class="A">

        A-3
            <input type="checkbox" value="A3" name="A3" id="A3" tabindex="3" class="A">

        A-6
            <input type="checkbox" value="A6" name="A6" id="A6" tabindex="6" class="A">

A: Using a regular CSS selector works:
$('input[type=checkbox]')

jQuery also has a special :checkbox selector for this:
$('input:checkbox')

If you want to narrow it down to the ones with your class A, you can just add that in the selector:
$('input.A[type=checkbox]')
$('input.A:checkbox')

Or if you have them all gathered under a node (a form with an id for example), you can also narrow it down using the second parameter of the selector function:
$('input:checkbox', '#my-form')

And with a class selector as well:
$('input.A:checkbox', '#my-form')


text:
Q: Passing data between Intents causes app to 'unexpectedly close' I am trying to transfer an int value between two activities using intents, but my app keeps crashing. When I comment out the transfer of any data and simply use an intent, everything seems to work. I cannot tell what is wrong.
Activity 1 (HeartRateActivity):
//Imports

public class HeartRateActivity extends Activity {
/** Called when the activity is first created. */
Button nextActivity;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    nextActivity = (Button)findViewById(R.id.nextActivity);

    nextActivity.setOnClickListener(new Button.OnClickListener(){

        @Override
public void onClick(View v) {
    Intent intent = new Intent(HeartRateActivity.this, NextActivity.class);
    intent.putExtra("age", 2);
    startActivity(intent);
}

    });

}
}

My NextActivity.java
package com.heartRate;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class NextActivity extends Activity {
TextView display;
public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.next);
       int age = getIntent().getIntExtra("age", 0);
       display = (TextView) findViewById(R.id.display);
       display.setText(age);
}
}

My AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.heartRate" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="7" />

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".HeartRateActivity"
            android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER"
                             />
        </intent-filter>
    </activity>
    <activity android:name=".NextActivity"
      android:label="@string/app_name" />
</application>
</manifest>

My main.xml (used by HeartRateActivity)
 <?xml version="1.0" encoding="utf-8"?>
  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
 >
 <TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
 />
 <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
 android:id="@+id/nextActivity" android:text="nextActivity"></Button>
</LinearLayout>

My next.xml(used by NextActivity) is similar and i dont think thats the issue...:
 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
 <TextView android:text="TextView" android:layout_width="wrap_content"
 android:layout_height="wrap_content" android:id="@+id/display"></TextView>

 </LinearLayout>

I would appreciate help in solving this issue! Thank you

A: Replace
display.setText(age);

with
display.setText(Integer.toString(age));

If you provide an int as a parameter, it uses it as a resource ID, which, in this case, obviously doesn't exist.

A: just try do like this.
display = (TextView) findViewById(R.id.display);
display.setText(Integer.toString(age));
and surely it will work

A: Make sure that your Id and Intent Destination all must be Ok.
then just put between intent from initialize ans start.
with put
intent.putExtra("age", Double);

from get this.
double d = getIntent().getStringExtra("age");

A: Make sure that R.id.display is a valid TextView in your next layout.

A: Just so we're clear, you're saying when you include the ...
intent.putExtra("age", 2);

in the sending Activity, and the ...
int age = getIntent().getIntExtra("age", 0);

in the receiving Activity, the application crashes or expereinces problems?  And, by excluding those 2 statements the application performs normally?  I'm just curious what does LogCat show?  Even though you application is crashing LogCat will have several entries as to what was happening just prior to the close.


text:
Q: Extra Apostrophes surrounding my string I try the following code:
print(repr("%0.2f" % cost).rjust(24), repr("%0.2f" % provision).rjust(17), end="\n")

but the resulting string I get is (when cost = 100.00 and provision = 4.00)
            '100.00'            '4.00'

So r.just is working perfectly (looked it up in here) but for some odd reason these apostrophes appeared around the values.
this doesn't happen in my next line of code:
print("Provision summ %0.2f euros." % summ)

which gives me
Provision summ 4 euros.

As you can see, no apostrophes, why is that? Can you advise me how to remove them? I have tried adding .remove("'", "") to my string, but it didn't help.

A: Do not use repr() here; it introduces the quotes because you are asking for the Python literal form of the strings. The end='\n' is entirely redundant too as that is the default. Grouping the format strings in parenthesis would do what you want:
print(("%0.2f" % cost).rjust(24), ("%0.2f" % provision).rjust(17))

or justifying before interpolating:
print("%0.2f".rjust(24) % cost, "%0.2f".rjust(17) % provision)

You perhaps would do better studying str.format() and use that to format and justify your text:
print("{:>24.2f}{:>18.2f}".format(cost, provision))

Here the >24 and >18 right-justify the value in a field 24 and 18 characters wide (the latter is 17 + the extra space print() adds when printing multiple arguments):
>>> cost, provision = 100.0, 4.0
>>> print("{:>24.2f}{:>18.2f}".format(cost, provision))
                  100.00              4.00

A: That's what repr does, though: shows a representation of the actual object. In this case, the object is the string composed of "%0.2f" % cost etc.
I have no idea why you would use repr here at all, especially when you're not doing so in the next, correct, line. It should just be:
print(("%0.2f" % cost).rjust(24) ... )

A: Why that double formatting (i. e. using %0.2f first and then again using rjust)?  You can do that in one step, that's what it is meant for:
print('%24.2%17.2f' % (cost, provision))

This is probably what you want.


text:
Q: Relationship while controlling for variables what does it mean when a question states controlling for other variables. for example I came across this question,
Estimate a quadratic relationship between lnhourpay and age, controlling for gender (sex), and years of schooling (edage).
does it mean to regress with variables lnhourpay age agesqr sex edage,
or
does it mean to regress with interactive variables lnhourpay age agesqr sex edage agesqr_sex agesqr_edage edage_sex.
I am confused what it means when questions states controlling for other variables?
I am doing basic econometric so please avoid advanced level explanations.


text:
Q: How to speed up the model's loading phase in tensorflow.js? System
Browser: Edge/Chrome;
tfjs version: 2.7.0;
Description
Load a trained MobileNet V2 model with tensorflow.js in a specific page take 10+ seconds one time.
Not only for the first time, but takes the same 10+ seconds every time I open the page.
When the loading phase is completed, the prediction phase is fast.
But I want to know how to speed up the loading phase, because it appears a not very good performance like this.
The code of loading below:
async function loadModel(model_path) {
    model = await tf.loadLayersModel(
        model_path
    );
}

The model size is only 9MB.

A: Have you updated the cdnjs tensorflow to the latest version? Check it out here
I had similar challenge and that worked for me.


text:
Q: ms outlook 2013 addressentry ID is not unique Everything I read about MS Outlook says the addressentry.id is unique.  but mine don't appear to be.
Here's some code:
Dim anaddressentry As AddressEntry
Dim listuniqueid As String
Dim lastlistunique As String
Dim kount As Integer
lastlistunique = "none"
For kount = 1 To 20
    For Each anaddressentry In Session.AddressLists.Item(2).AddressEntries
        If anaddressentry.Name = "testcontactgroup" Then
            listuniqueid = anaddressentry.ID
            If lastlistunique <> "none" Then
                If lastlistunique <> listuniqueid Then
                    Stop
                End If
            End If
            lastlistunique = listuniqueid
        End If
    Next
Next

It runs the same routine 20 times where it goes through my contacts and looks for something with the name "testcontactgroup"  then it gets it's addressentry.id.  If this isn't the first time, it compares it with the last addressentry.id it got for that contact.
If they aren't the same, it stops.  As I understand it, they should always be the same.
They're close to the same, except for the last few characters.
here are two values I get for the id for the same address entry
00000000FE42AA0A18C71A10E8850B651C2400000300000005000000FF000000180000000000000058D0304A0573A945BD70D6FBA5D114FAC416A000000090
00000000FE42AA0A18C71A10E8850B651C2400000300000005000000FF000000180000000000000058D0304A0573A945BD70D6FBA5D114FAC416A00060209B
Any suggestions?
thanks
bob

A: That entry id refers to a contact in one of your Contacts folders. It includes (besides a few flags) the email kind (email1, email2, fax, etc.). and the entry id of the corresponding IPM.Contact message (ContactItem object).
You should never directly compare entry ids - that is what Namespace.CompareEntryIDs is for: multiple entry ids can refer to the same object.


text:
Q: Java FX Circle Image I hope you can help me. I'm trying to round a image retrieved from my database. In the next image you can see the image is correctly displayed in a imageview. User selects a new item in the table and the image change to display the correct image, this is working, no problems here.
This is the program
I try with this code in the gestionarEventos :
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());
        Image im = imgfotovisi.getImage();
        circulo.setFill(new ImagePattern(im));

But java say :
... 58 more
Caused by: java.lang.NullPointerException: Image must be non-null.
    at javafx.scene.paint.ImagePattern.<init>(ImagePattern.java:235)

The program runs if I delete the lines below the
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());

line.
When it runs, I don't know why says the image is null, when I can see clearly there.
This is ver_visitantes class:
   import java.net.URL;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.util.ResourceBundle;
    import java.util.function.Predicate;
    import javafx.beans.property.ReadOnlyStringWrapper;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.collections.transformation.FilteredList;
    import javafx.collections.transformation.SortedList;
    import javafx.concurrent.Service;
    import javafx.concurrent.Task;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.Node;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableView;
    import javafx.scene.control.TextField;
    import javafx.scene.image.Image;
    import javafx.scene.image.ImageView;
    import javafx.scene.input.InputEvent;
    import javafx.scene.layout.StackPane;
    import javafx.scene.paint.Color;
    import javafx.scene.paint.ImagePattern;
    import javafx.scene.shape.Circle;

    import javafx.stage.Stage;

    public class ver_visitantes implements Initializable {

        @FXML   private TableView<visitantes> tbvisitantes;
        @FXML   private TableColumn<visitantes, String> clcedula,clnombres,clapellidos,clapartamento,clcelular,clobservaciones;
        @FXML   private ImageView imgfotovisiact,imgfotoact,imgfotovisi,imgfoto;
        @FXML   private TextField txtcedula,txtnombres,txtapto,txtapellidos,txtapt,txtcelular,txtobservaciones;
        @FXML   private Label lblinfovisiact,lblusuario,lblstatusvisi;
        @FXML   private Circle circulo;

        private ObservableList<visitantes> visitorlist;

        @Override
        public void initialize(URL arg0, ResourceBundle arg1) {

            ConexionSQL cnt = new ConexionSQL();
            cnt.conexion();

            visitorlist = FXCollections.observableArrayList();
            visitantes.llenarlistavisitas(cnt.conexion(), visitorlist);
            tbvisitantes.setItems(visitorlist);// llenar table view con la lista

            clcedula.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcedula()));
            clnombres.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getnombres()));
            clapellidos.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapellidos()));
            clapartamento.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getapartamento()));
            clcelular.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getcelular()));
            clobservaciones.setCellValueFactory(cellData -> new ReadOnlyStringWrapper(cellData.getValue().getobservaciones()));

            gestionarEventos();

            tbvisitantes.getSelectionModel().selectFirst();

        }

        public void gestionarEventos() {
            tbvisitantes.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<visitantes>() {
                @Override
                public void changed(ObservableValue<? extends visitantes> arg0, visitantes valorAnterior,
                        visitantes valorSeleccionado) {
                    imgfoto.setVisible(false);
                    btnmodificar.setDisable(false);
                    btncancelar.setDisable(false);
                    btneliminar.setDisable(false);
                    imageRetrievalService.restart();

                    if (valorSeleccionado != null) {

                        txtcedula.setText(String.valueOf(valorSeleccionado.getcedula()));
                        txtnombres.setText(valorSeleccionado.getnombres());
                        txtapellidos.setText(valorSeleccionado.getapellidos());
                        txtapto.setText(String.valueOf(valorSeleccionado.getapartamento()));
                        txtcelular.setText(String.valueOf(valorSeleccionado.getcelular()));
                        txtobservaciones.setText(String.valueOf(valorSeleccionado.getobservaciones()));
                    }
                }
            });

        imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());

         }

        private final Service<Image> imageRetrievalService = new Service<Image>() {// cargar imagen en visitantes
            @Override
            protected Task<Image> createTask() {
                final String id;

                final visitantes visitante = tbvisitantes.getSelectionModel().getSelectedItem();
                if (visitante == null) {
                    id = null;
                } else {
                    id = visitante.getcedula();
                }
                return new Task<Image>() {
                    @Override
                    protected Image call() throws Exception {
                        if (id == null) {
                            return null;
                        }
                        return visitante.getImageById(id);
                    }
                };
            }
        };

    }

this is the visitantes class,called from the imageRetrievalService to get the image:
package application;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.ObservableList;
import javafx.scene.image.Image;

public class visitantes {
    private StringProperty cedula;
    private StringProperty nombres;
    private StringProperty apellidos;
    private StringProperty apartamento;
    private StringProperty celular;
    private StringProperty observaciones;

    public visitantes(String cedula,String nombres,String apellidos,String apartamento,String celular,String observaciones){

        this.cedula = new SimpleStringProperty(cedula);
        this.nombres = new SimpleStringProperty(nombres);
        this.apellidos = new SimpleStringProperty(apellidos);
        this.apartamento = new SimpleStringProperty(apartamento);
        this.celular = new SimpleStringProperty(celular);
        this.observaciones = new SimpleStringProperty(observaciones);

    }

    public String getnombres(){
        return nombres.get();
    }

    public void setnombres(String nombres){
        this.nombres = new SimpleStringProperty(nombres);
    }

    public String getcedula(){
        return cedula.get();
    }

    public void setcedula(String cedula){
        this.cedula = new SimpleStringProperty(cedula);
    }
    public String getapellidos(){
        return apellidos.get();
    }

    public void setapellidos(String apellidos){
        this.apellidos = new SimpleStringProperty(apellidos);
    }

    public String getapartamento(){
        return apartamento.get();
    }

    public void setapartamento(String apartamento){
        this.apartamento = new SimpleStringProperty(apartamento);
    }

    public String getcelular(){
        return celular.get();
    }

    public void setcelular(String celular){
        this.celular = new SimpleStringProperty(celular);
    }

            public Image getImageById(String id) throws SQLException, IOException  {
                try (
                        ConexionSQL cn = new ConexionSQL();
                        Connection con = cn.conexion();
                    PreparedStatement ps = con.prepareStatement(
                        "SELECT foto_visi FROM visitantes WHERE cedula_visi = ?");
                ) {
                    ps.setString(1, id);
                    ResultSet results = ps.executeQuery();
                    Image img = null ;
                    if (results.next()) {
                        Blob foto = results.getBlob("foto_visi");
                        InputStream is = foto.getBinaryStream();
                        img = new Image(is) ; // false = no background loading
                        is.close();
                    }
                    results.close();
                    return img ;
                } catch (Throwable e) {
                    String info = e.getMessage();
                    System.out.println(info);
                }
                return null;
            }
   }

I think the problem is here:
imgfotovisi.imageProperty().bind(imageRetrievalService.valueProperty());

I don't know if the retrieved image is loaded in the imageivew in this line. Looks like yes, but if I do
Image im = imgfotovisi.getImage();

Java says it is null. Then I can't get the image into the circle.
Thanks in advance :)

A: bind isn't going to load an image itself, it will just bind so that one variable will change when the source changes (in this case the value property of the service), which isn't going to happen straight away as the service is running asynchronously.  So, if you query the value straight away after issuing the bind statement, you won't get the result you are expecting, as the source hasn't yet changed.
Instead you need to take action only once the image is actually available.
For instance:
imageRetrievalService.valueProperty().addListener((obs, oldVal, newVal) ->
    if (newVal != null)
        circulo.setFill(new ImagePattern(newVal))
);

Or, if you don't want a direct linkage to the service, and given that the imgfotovsi image property is already bound to the service value:
imgfotovisi.imageProperty().addListener((obs, oldVal, newVal) ->
    if (newVal != null)
        circulo.setFill(new ImagePattern(newVal))
);


text:
Q: What is a Chain rule for gradient? If $f:\mathbb R \to \mathbb R$ and $g:\mathbb R \to \mathbb R$ be defirrentiable funtion then we know that the composition funtion $h=g\circ f$ is diffentiable and $$\frac{d}{dx} h(x)= h'(x)= f'(g(x)) \cdot g'(x) $$ (Here $\cdot $ denotes the real number multiplication)
Suppose that $f:\mathbb R^{n} \to \mathbb C$ and $g:\mathbb C \to \mathbb C.$ Consider composition function $h:\mathbb R^{n} \to \mathbb C$ as $h(x)= g\circ f(x)$ for $x\in \mathbb R^n.$

My Question: (1) What is the anologe of the above formula in higher dimension?
   (2) What is a gradient of $h= g\circ f:\mathbb R^n \to \mathbb C$? In other words, what is, keeping  the above formula in mind,  $\nabla h (x)$, ($x\in \mathbb R^n$)? Can we say $\nabla h(x)= \nabla g (f(x)) \cdot \nabla u (x)$ and now what is a meaning of $\cdot $ here?

A: It is easier to view $\mathbb{C}$ as $\mathbb{R}^2$ unless you assume analyticity. Looking at it this way, $g$ and $f$ both have Jacobian matrices $J_f : \mathbb{R}^n \to \mathbb{R}^2$ and $J_g : \mathbb{R}^2 \to \mathbb{R}^2$ and you have $J_{g \circ f}(x)=J_g(f(x)) J_f(x)$ (where concatenation denotes matrix multiplication or equivalently composition of linear maps). If in fact $g$ is a holomorphic function then $J_g$ is isomorphic to the complex-valued function $g'$ by the isomorphism $a+bi \sim \begin{bmatrix} a & -b \\ b & a \end{bmatrix}$.


text:
Q: Find specific server in iPhone Hi i am developing iPad client server based application. It is required in application that when application starts it searches for specific server. If server found then connect with it and start consuming webservices on that server.
The point is user should not enter IP address of server. Application search servers and connect with specific server. Is there anyway to find server.

A: Apple has a technology called Bonjour which is designed for this kind of thing.
http://www.apple.com/support/bonjour/
http://my.safaribooksonline.com/book/programming/iphone/9780470918029/bonjour-programming/browsing_for_services
If you want a simpler solution, you could just use a DNS entry with a CNAME or A record pointing to the server.


text:
Q: How can I call a PHP file with GET on an AJAX request? I am trying to get data back from a PHP file assigned with GET parameters in an AJAX request:

xmlhttp.open("GET","getMyData.php?name="+name+"&email="+email,true);

Can I call the getMyData.php like that, or it has to be in the root of the project? Now is in the same directory as the javascript file.
Also, if possible, a small example of how to insert the returned data into an input field.
Thanks a bunch!

A: Here the example
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
  //xmlhttp.responseText; //content
  document.getElementById("myDiv").innerHTML=xmlhttp.responseText; //write inside myDiv
}
}
xmlhttp.open("GET","getMyData.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+name+"&email="+encodeURIComponen(email));
xmlhttp.send();
}

Look here  get more information and example

A: Have a look at relative and absolute paths. You will understand how the /, ../ etc. work. You will also see that your example is correct if the PHP file is in the same folder as your web page where the javascript is executed.
About the last part, I'm cutting off a little bit the code (that you can find fully here for example), but here is the point:
if (xhr.readyState === 4 && xhr.status === 200) {
    // The datas returned by PHP are in the variable 'xhr.responseText' or 'xhr.responseXml'.
    // In this case you can add straight the HTML into a DIV, but you usually have datas in JSON.
    // To "transform" your JSON string into a javascript object, use the following:
    //     var obj = JSON.parse(xhr.responseText)
    document.getElementById("myDiv").appendChild(xhr.responseXml) // Don't use 'innerHTML', it is evil.
}


text:
Q: How to use jar file in Ruby Mine I have one Java Jar file that I am able to use successfully in my selenium framework. I would like to use the same jar file in my Ruby automation. Can anyone help me ?
Note: I am using PDF-util jar file (To compare two pdf's, pixel to pixel)

A: If you really want to use that jar, then you probably can use %x() or backticks to use your jar from test by calling like java -jar /path/to/PDF-util.jar some args here.
Also you may want to have a look at ImageMagick gem, it might do what you need.
And if it's enough to compare binary files, the original and the one you can download in your test, you may compare their hash sums and it should be enough.


text:
Q: Least complete Solutions I know what least residues are and I can solve them, but apparently, for an equation like this:
$$x^2 + x + 1 \equiv 0 \mod 195,$$
you have to find the least complete solutions.
I tried looking for an example online but couldn't find anything. Please help.
Thanks in advance.

A: $195=3\cdot 5\cdot 13 \mid x^2+x+1$ implies $5\mid x^2+x+1$. The polynomial $x^2+x+1$ is irreducible over $\mathbb{F}_5$, in particular it has no root in $\mathbb{F}_5$. Indeed, just try all elements of $\mathbb{F}_5$. So there is no solution modulo $195$ (there is a solution modulo $3$ with $x=1$, and a solution modulo $13$ with $x=3$ or $x=9$).

A: Since the modulus is composite, you solve the equation mod $3,5,13$ then combine with the CRT.  The moduli are so small you can do it by inspection (i.e. trying each number in turn).


text:
Q: How to programmatically get current keyboard language on an Android device I am writing an application which is using dictionaries. I want to switch between dictionaries any time user change input language. For example if the typing language is english work with english dictionary, if it is german, work with german dictionary. Is there any way to set a listener to get that change? All the answer i found were about locale and not about input language. I don't want to handle locale, locale has no effect in application, the input language does. (I am developing in minSDK=7)

A: It is possible
imm.getCurrentInputMethodSubtype();

to return you null value. In this case you should check language of android system like this
Locale.getDefault().getLanguage()        ---> en

otherwise you will receive NullPointerException

A: InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);

InputMethodSubtype ims = imm.getCurrentInputMethodSubtype();

String locale = ims.getLocale();

You can try this code to get Current Keyboard Language regional code.


text:
Q: how to split records returned from a query into sets of 1000 via jdbc I have a source and a target database and I need to check the count in both, is it same or not.
I fetch a column from source database via below queries:
DMS_Arr[0] = "select count(distinct eai_src_pk) from document_id_creation where eai_entry_date > (trunc(sysdate-1) + 00/24) and eai_entry_date < (trunc(sysdate) + 00/24)";
DMS_Arr[1] = "select distinct eai_src_pk from document_id_creation where eai_entry_date > (trunc(sysdate-1) + 00/24) and eai_entry_date < (trunc(sysdate) + 00/24)";

Now I store the output of DMS_Arr[1] into a variable "targetPk" separated by commas and use it in my JDBC query to check the count at target side via the below query.
ERP_Arr[0] ="select count(distinct eai_src_pk) from xxindus.XXINDUS_ERP_OBRM_PYMT_CNDN_T where eai_src_pk in (" + targetPk + ")" + " and eai_entry_date > (trunc(sysdate-1) + 00/24)";

However, the problem is that the records in variable targetPk could be 1000, 10000 or 150000 and database is able to handle only 1000 at a time. How can I make my code handle this and automatically split them into sets of 1000 so that JDBC query does not throw any error. Then I need to store all these values returned into a string variable separated by commas and check the count.


text:
Q: Fortran output file write data in columns rather than rows I'm trying to output data to a file. When I run the Fortran code, the data is written like in the  picture below.

The data seems to be writing across the rows. I would like so that it writes in columns under the headings I have provided which are Fragment Number, Index, X_POS, Y_POS, Time, X_VEL and Y_VEL.
Any help would be greatly appreciated.
     SUBROUTINE EXEDIT

  USE kindef
  USE wrapup
  USE mdgrid
  USE ranges
  USE kindef
  USE cycvar        ! STORES THE CYCLE VARIABLES (E.G. TIME)
  USE subdef
  USE fildef
  USE matdef        ! STORES ALL RELEVANT MATERIAL ASSIGNMENTS AND DETAILS
  USE material

  IMPLICIT NONE

  ! Define user variables
  INTEGER (INT4)    ::  NS,I,J,IJK,counter
  REAL (REAL8)  ::  Y_LIMIT,POS_X,POS_Y,SIM_TIME,VEL_X,VEL_Y

   ! Specify the output files
   ! Desired output is a text file which lists the relevant variables for each fragment, i.e.
  !  Fragment   Mat-ID  Part    Index   X_POS   Y_POS   Z_POS   Time    X_VEL   Y_VEL   Z_VEL   Mass

  open(99,FILE=trim(FNID)//'.dat')
  write (99, '(A15)',advance='no')'Cycle no: '
  write (99, '(I10)',advance='yes')NCYCLE
  write (99, '(A15)',advance='yes')' '
  write (99, '(A15)',advance='no')'Fragment'
  write (99, '(A15)',advance='no')'Index'
  write (99, '(A15)',advance='no')'X-POS'
  write (99, '(A15)',advance='no')'Y_POS'
  write (99, '(A15)',advance='no')'Time'
  write (99, '(A15)',advance='no')'X_VEL'
  write (99, '(A15)',advance='no')'Y_VEL'
  write (99, '(A15)',advance='yes')' '

  ! SETTING THE VARIABLES EQUAL TO 0
  !   POS_X = 0
  !   POS_Y = 0
  !   POS_Z = 0
  !   VEL_X = 0
  !   VEL_Y = 0
  !   VEL_Z = 0
  !   NODE_MASS = 0
  counter = 0 !The variable count is initialized to 0

  ! Defining the z-boundary
    Y_LIMIT=0

  ! Initialization of arrays
  ! This set of loops generates a variable array IJK which defines each IJK index in each part
    DO NS=1,NUMSUB
    NSUB=NS
    CALL GETSUB
        DO I=1,IMAX
            DO J=1,JMAX
                    IJK=IJSET(I,J)
            END DO
        END DO
    END DO

  ! Determining the fragment variables
    DO NS = 1, NUMSUB ! From NS = 1 to the Number of Parts in problem.
    NSUB = NS
    CALL GETSUB
    CALL GETMAT
        DO I = 1,IMAX
            DO J = 1,JMAX
                    IJK=IJSET(I,J)
                    SIM_TIME=0
                    IF ((YN(IJK).LE.Y_LIMIT).AND.(SIM_TIME==0)) THEN
                            counter=counter+1
                            SIM_TIME=TIME !TIME is an already defined variable - CURRENT TIME
      ! Fragment    Index   X_POS   Y_POS   Time    X_VEL   Y_VEL
                            write(99,'(I15)',advance='no')counter
                            write(99,'(I15)',advance='no')IJK
                            write(99,'(F15.5)',advance='no')XN(IJK)
                            write(99,'(F15.5)',advance='no')YN(IJK)
                            write(99,'(F15.5)',advance='no')TIME
                            write(99,'(F15.5)',advance='no')UXN(IJK)
                            write(99,'(F15.5)',advance='no')UYN(IJK)
                    END IF
                END DO
            END DO
        END DO

  CLOSE(99)

  RETURN

  END SUBROUTINE EXEDIT


text:
Q: sklearn: Found arrays with inconsistent numbers of samples when calling naive_bayes.MultinomialNB( I have looked at similar questions as such as this one. But none of the mentioned solutions worked in my case.
I am trying to build a text classification prediction model.
def train_model(classifier, feature_vector_train, label, feature_vector_valid, is_neural_net=False):
    # fit the training dataset on the classifier
    classifier.fit(feature_vector_train, label)

    # predict the labels on validation dataset
    predictions = classifier.predict(feature_vector_valid)

    if is_neural_net:
        predictions = predictions.argmax(axis=-1)

    return metrics.accuracy_score(predictions, train_label)

# Naive Bayes on Word Level TF IDF Vectors
accuracy = train_model(naive_bayes.MultinomialNB(),train_text,train_label,test_text)

print ("NB, WordLevel TF-IDF: ", accuracy)

However, Naive_bayes returns the below error:
ValueError: Found input variables with inconsistent numbers of samples: [500, 3100]

my training data
print(train_text.shape)
type(train_text)

returns
(3100, 3013)
scipy.sparse.csr.csr_matrix

my training labels
print(train_label.shape)
type(train_label)

returns
(3100,)
numpy.ndarray

my test dataset
print(test_text.shape)
type(test_text)

returns
(500, 3013)
scipy.sparse.csr.csr_matrix

I tried every possible type of transformation. Can any one recommend a solution? thanks

A: I guess the problem is in
predictions = classifier.predict(feature_vector_valid)
return metrics.accuracy_score(predictions, train_label)

What is the shape of predictions? Is train_label a global variable in train_model? Also, is prediction has the same shape as train_label?


text:
Q: Decrypting file in C++, which was encrypted with openssl -aes-128-cbc I'm trying to decrypt a file in C++. This file is encrypted with the following command:
openssl enc -nosalt -aes-128-cbc -pass pass:test -in "test.txt" -out "test_enc.txt" -p

The console shows the key=098F6BCD4621D373CADE4E832627B4F6 and iv=0A9172716AE6428409885B8B829CCB05.
In C++ I have included the #include openssl/aes.h line and try to decrypt with the following code:
const char *indata = string.toAscii().constData();

unsigned char outdata[strlen(indata)];

unsigned char ckey[] = "098F6BCD4621D373CADE4E832627B4F6";
    unsigned char ivec[] = "0A9172716AE6428409885B8B829CCB05";

    /* data structure that contains the key itself */
    AES_KEY key;

    /* set the encryption key */
    AES_set_decrypt_key(ckey, 256, &key);

    AES_cbc_encrypt((unsigned char*) indata, outdata, strlen(indata), &key, ivec, AES_DECRYPT);

    QString result = QString((const char*) outdata);

    return result;

The variable outdata contains different value than before encryption with OpenSSL.

A: You specify -aes-128-cbc as an option on OpenSSL so the key and initialization vector will be 128 bits long. openssl prints these out as hex strings, as they would be obfuscated on the console if printed binary.
Therefor you should initialize your ckey[] and ivec[] as the binary value of the hex strings like this:
unsigned char ckey[] = "\x09\x8F\x6B\xCD\x46\x21\xD3\x73\xCA\xDE\x4E\x83\x26\x27\xB4\xF6";
unsigned char ivec[] = "\x0A\x91\x72\x71\x6A\xE6\x42\x84\x09\x88\x5B\x8B\x82\x9C\xCB\x05";

and also, use key length 128 instead of 256 in:
AES_set_decrypt_key(ckey, 128, &key);

A: OpenSSL creates the key using the password you offer, and also the vector you specified is related to decryption and encryption. Make sure you have the same key and vector while decrypting the text.


text:
Q: What is LINQ to events a.k.a RX Framework? What is LINQ to events a.k.a RX Framework aka the Reactive Extensions in .NET 4.0 (but also available as backported versions)?
In other words, what is all the stuff in System.Reactive.dll for?

A: You can read more about it here:
http://themechanicalbride.blogspot.com/2009/07/introducing-rx-linq-to-events.html
My first exposure was on this blog, as I am reading his book on F#:
http://tomasp.net/articles/reactive-ii-csevents.aspx
Basically my understanding of it is that when you write an event handler for mouse movements, for example, you may want to continuously capture these events, and perhaps be able to count how many movements or clicks, but, basically, you want to use that information in more ways than just as an event handler.  So, just treat the events as a continuous stream.

A: Also, check out this Channel 9 video: Expert to Expert: Brian Beckman and Erik Meijer - Inside the .NET Reactive Framework (Rx)
From the show description:

The .NET Reactive Framework (Rx) is the mathematical dual of LINQ to
  Objects. It consists of a pair of
  interfaces IObserver/IObservable that
  represent push-based, or observable,
  collections, plus a library of
  extension methods that implement the
  LINQ Standard Query Operators and
  other useful stream transformation
  functions.

A: I think the essence of the RX is changing the angle with which we look at information. Naturally, every piece of information is a result of some process, which takes place in the time-space continuum. Traditional approach works with the projection of the process to the "current" time plane, losing the details of the time dimension as the result.
RX works with the projection to some other dimension, capturing the time component as well, so it is no wonder LINQ to RX is a superset of the regular LINQ.

A: .NET Rx team (this is not an official name) found that any push sequence (events, callbacks) can be viewed as a pull sequence (as we normally do while accessing enumerables) as well – or they are Dual in nature. In short observer/observable pattern is the dual of enumeration pattern.
So what is cool about about this duality?
Anything you do with Pull sequences (read declarative style coding) is applicable to push sequences as well. Here are few aspects.
You can create Observables from existing events and then use them as first class citizens in .NET – i.e, you may create an observable from an event, and expose the same as a property.
As IObservable is the mathematical dual of IEnumerable, .NET Rx facilitates LINQ over push sequences like Events, much like LINQ over IEnumerables
It gives greater freedom to compose new events – you can create specific events out of general events.
.NET Rx introduces two interfaces, IObservable and IObserver that "provides an alternative to using input and output adapters as the producer and consumer of event sources and sinks" and this will soon become the de-facto for writing asynchronous code in a declarative manner. Here is a quick example.
//Create an observable for MouseLeftButtonDown

var mouseLeftDown=Observable.FromEvent<MouseButtonEventArgs>
        (mycontrol,"MouseLeftButtonDown");

//Query the above observable just to select the points
var points = from ev in mouseEvents
                 select ev.EventArgs.GetPosition(this);

//Show points in the window's title, when ever user
//presses the left button of the mouse
points.Subscribe(p => this.Title = "Location ="
                                        + p.X + "," + p.Y);

You may go through these posts as well to get the head and tail in detail. Also have a look at the relates source code as well.

*

*Part I - System.Reactive or the .NET Reactive Extensions (Rx) – Concepts and First Look

*Part II - LINQ To Events - More on .NET Reactive Extensions (Rx)

*Part III - LINQ To Events - Generating GetEventName() Wrapper Methods using T4 Text Templates
Check out this set of articles


text:
Q: Trying to set a channel and message environment variable globally in a Jenkinsfile but not sure which of two methods are best Trying to make SEND_SLACK_NOTIF, SLACK_CHANNEL and SLACK_MESSAGE variables and set them as environment variables globally in Jenkins file but I'm not sure which method is superior in a multi-stage pipeline. Don't mind the indenting!
Method 1:
 #!/usr/bin/groovy

    node('large') {

    withEnv(['SEND_SLACK_NOTIF=true',
            'SLACK_CHANNEL=UT24K22K1',
            "SLACK_MESSAGE=FAILURE: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'\nBetter fix it! (${env.BUILD_URL})"]){
        stage('Test') {
            if (env.SEND_SLACK_NOTIF) {
                slackSend channel: env.SLACK_CHANNEL, color: 'danger', message: env.SLACK_MESSAGE, tokenCredentialId: 'slack-integration-token'
            }
        }
    }
}

Method 2:
 #!/usr/bin/groovy
    env.SEND_SLACK_NOTIF = true
    env.SLACK_CHANNEL = 'UT24K22K1'
    env.SLACK_MESSAGE = "FAILURE: Job '${env.JOB_NAME} [${env.BUILD_NUMBER}]'\nBetter fix it! (${env.BUILD_URL})"

node('large') {

stage('Test') {
            if (env.SEND_SLACK_NOTIF) {
                slackSend channel: env.SLACK_CHANNEL, color: 'danger', message: env.SLACK_MESSAGE, tokenCredentialId: 'slack-integration-token'
            }
        }
    }

A: If you just consider your two options, I'd go with option 1 because it's more declarative than option 2. However the superior way is the one described in the Jenkins documentation:
pipeline {
    agent {
        ...
    }

    environment {
        SEND_SLACK_NOTIF = 'true'
        SLACK_CHANNEL = 'UT24K22K1'
    }

    stages {
        ...
    }
}

You might also want to reconsider which variables you really need. If you only use them once, don't use a variable, but use the value directly.


text:
Q: Entity Framework: One to zero relationship I've got
public class MyUser : IdentityUser<int,MyLogin,MyUserRole,MyUserClaim>
{
     public virtual MyUserProfile Profile { get; set; }
}

public class MyUserProfile
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
}

My implementation of IdentityUser has INT PK. I want to have one navigation property in MyUser and don't have on the other side. I prefer data annotations. Is it possible to use IdentityUser PK for navigating? (EF v 6.1.3)
UPD #1.
Dependent type - MyUserProfile. And it DOES NOT have to contain navigation property of MyUser type.

A: I'd question why it is you're doing this, a better solution may be to keep it on a single table as it will be faster unless they are both massive entities and the profile is optional (but even then, you could have a separate column stating that the extra data is or isn't available).
Since you seem to be asking for a 1:0..1 relationship you can implement it as follows. I know you wanted Data Annotations, but I'd really recommend being explicit here*, so that any changes to your model won't cause a potentially unintended knock-on effect.
public class MyUser : IdentityUser<int,MyLogin,MyUserRole,MyUserClaim>
{
     public virtual MyUserProfile Profile { get; set; }
}

public class MyUserProfile
{
     public int Id { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }

     public MyUser User { get; set; }
}

On your DbContext, override OnModelCreating with the following:
modelBuilder.Entity<MyUserProfile>()
            .HasRequired(m => m.User)
            .WithOptional(m => m.Profile);

** Full disclosure: I also always prefer Data Annotations over the Fluent Configuration Syntax, but I haven't avoided it to date and there's really no downside to it. For something as fundamental as this, you don't want it to be affected by a slight change in attribute.
This generates the following schema that keeps things lean as the IDs are synchronised between the two tables as we'd expect:
        CreateTable(
            "dbo.MyUsers",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Test = c.String(),
                })
            .PrimaryKey(t => t.Id);

        CreateTable(
            "dbo.MyUserProfiles",
            c => new
                {
                    Id = c.Int(nullable: false),
                    Test = c.String(),
                })
            .PrimaryKey(t => t.Id)
            .ForeignKey("dbo.MyUsers", t => t.Id)
            .Index(t => t.Id);

As @grek40 mentioned, it can be done without the navigation property on the other end by flipping the fluent configuration of the relationship (see the comment for more info), see grek40's answer for that option.

A: I want to mention a slight difference of my tests compared to the answer of @RudiVisser regarding the created database.
public class MyUser
{
    public int Id { get; set; }

    public virtual MyUserProfile Profile { get; set; }
}

public class MyUserProfile
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

class MyContext : DbContext
{
    public DbSet<MyUser> Users { get; set; }
    public DbSet<MyUserProfile> Profiles { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyUser>()
            .HasOptional(x => x.Profile)
            .WithRequired();
    }
}

Generated Migration
public override void Up()
{
    CreateTable(
        "dbo.MyUserProfiles",
        c => new
            {
                Id = c.Int(nullable: false),
                FirstName = c.String(),
                LastName = c.String(),
            })
        .PrimaryKey(t => t.Id)
        .ForeignKey("dbo.MyUsers", t => t.Id)
        .Index(t => t.Id);

    CreateTable(
        "dbo.MyUsers",
        c => new
            {
                Id = c.Int(nullable: false, identity: true),
            })
        .PrimaryKey(t => t.Id);
}

In contrast to his answer, I don't observe the creation of a separate MyUser_Id foreign key. The MyUserProfiles.Id is correctly configured as primary key and foreign key. So anyone who wants to use such a configuration should give it a try but carefully observe the generated migration code.
My toolset: Visual Studio 2013, EntityFramework 6.1.3 nuget package.

A: I'm note sure if you want that, but you can "split table".
In other words use the same table for the two entities.
Like this:
[Table("MyUser ")]
public class MyUser : IdentityUser<int,MyLogin,MyUserRole,MyUserClaim>
{
     public virtual MyUserProfile Profile { get; set; }
}

[Table("MyUser ")]
public class MyUserProfile
{
     [Key]
     public int Id { get; set; }

     public string FirstName { get; set; }
     public string LastName { get; set; }
}


text:
Q: database strategy to provide data analytics I provide a solution that handles operations for brick and mortar shops. My next step is to provide analytics for my customers.
As I am in the starting phase I am hoping to find a free way to do it myself instead of using third party solutions. I am not expecting a massive scale at this point but I would like to get it done right instead of running queries off the production database.
And I am thinking for performance concerns I should run the analytics queries from separate tables in the same database. A cron job will run every night to replicate the data from the production tables to the analytics tables.
Is that the proper way to do this?
The other option I have in mind is to run the analytics from a different database (as opposed to just tables). I am using Amazon RDS with MySQL if that makes it more convenient?

A: It depends on how much analytics you want to provide.
I am a DWH manager and would start off with a small (free) BI (Business Intelligence) solution.
Your production DB and analytics DB should always be separate.

*

*Take a look at Pentaho Data Integration (Community Edition) It's a free ETL tool that will help you get your data from your production to your analytics database and also can perform transformation.

*check out some free reporting software like Jaspersoft to help you provide a Reporting Platform for customers (if that's what you want, otherwise just use Excel).

*BI never wants to throw away data. If you think that your data in the analytics DB is gonna grow large (2TB +) don't use MySQL but rather PostgreSQL. MySQL does not handle big data well.

*If you are really serious about this, read "The Datawarehouse Toolkit" by Ralph Kimball. That will set you up with some basic Data Warehouse knowledge.

A: Amazon RDS provides something call a Read-Replica. Which automatically performs replication and is optimised for reading.
I like this solution for its high convenience. Downside: its price-tag.


text:
Q: Choosing hyperparameters automatically I'm studying neural networks, and regularization. I noticed that there are a lot of hyperparameters that needs to be set manually depending on the type of problem you're trying to solve, data sets that you're dealing with, etc.
I'm wondering if there is a way we can create another optimization model so that it automatically finds the best hyperparameters needed for training? I mean, we are able to find the appropriate weights by gradient descent, or other methods. So, if we are able to find some kind of cost function on the hyperparameters, won't we be able to do the same? Basically like an AI program adjusting our AI model.
Is something like this possible, or at least a valid question to ask? Maybe is this already done in some research that I'm not aware of?

A: Yes, there are frameworks available that will automatically tune hyper parameters for you. I'm on the Optuna team, and Optuna (optuna.org) is one such framework that will do Bayesian optimization to adjust hyper parameters for you. It can work with any python program that can be written with a loss or accuracy output.

A: There are some packages you can explore. I would recommend you to use talos.
Please find the link below:
https://www.analyticsvidhya.com/blog/2021/05/neural-network-and-hyperparameter-optimization-using-talos/
At the last you will find the codes for talos


text:
Q: Deploying Laravel 5.4 to Shared Hosting I've got a real head-scratcher for you! I've been working on a Laravel 5.4 application for quite some time now and up until yesterday I had been able to:

*

*develop on my local machine [still works flawlessly],

*push my changes to my BitBucket repo [still okay here],

*and would subsequently pull those changes to my shared hosting server (RedHat) [still running smoothly],

*I then run my dependency managers (npm and composer) to get the project in place and functional

*there is some matter with clearing various caches:

*

*php artisan view:clear

*php artisan route:clear

*php artisan cache:clear

*composer dump-autoload

*and finally move my '/public' folder to the web root and update index.php to point back to the 'bootstrap/autoload.php' in main project structure,

*I am aware there is likely another or several steps I am missing, but I am unsure what they are...
All that being said, I've attempted to deploy a number of applications using Laravel lately and I always seem to run into the same issue come time to deploy an application to production. I've read 30+ tutorials on the matter and nothing seems to explain the issue why my site isn't working any more.

*

*I've checked the error log file maintained by Apache, it's empty.

*

*Was wondering if it's a permissions issue, doesn't seem to be the case (all folders set to 775 and files set to 664 as specified by various sources and owned by serverName:userName)

*Browser console simply shows a 500 server error.

*All I see if "Whoops, looks like something went wrong." twice.

*

*There must be some way to show better error details (config debug setting already set to true)

Any suggestions at this point would be beneficial to send me looking in the right direction!
======= UPDATES =======
For the sake of thoroughness, and that this save others from severe headaches, I'll be posting actions taken here.

*

*Following tutorial mentioned by @user123456 (permissions applies)

*Generate new key for application

*Run php artisan config:clear

*Off to the races, answer to come!

A: You need to ensure you have a working .env file.
Once done, run php artisan key:generate to create a key for your application after which you should clear your application's cache as follows php artisan config:clear

A: I would never recommend using shared hosting for Laravel application. You will face lots of issues for permissions, composer and external dependencies. Instead, you can use cloud servers like DigitalOcean, Linode, vultr and deploy laravel application on them. If you don't know about linux and creating Stacks you can use Cloudways to deploy laravel.
https://dev.to/rizwan_saquib/deploy-laravel-application-on-cloud-easily-with-cloudways


text:
Q: How to Split and bind json return Datetime key & value into Input text box First, I have 3 input text box (day, month, year). I made Json return from my controller and I made a key & value binding function with jquery. The problem is I don't know how to split Datetime value into day, month, year and bind to my inputs because that Datetime value is looks like
EntryDate: "/Date(940786200000)/"
My Controller
        [HttpGet]
        public ActionResult getBookById(int? id)
        {
            TB_EnglishBooks tbook = db.TB_EnglishBooks.Where(x => x.ItemID == id).FirstOrDefault();
            return Json(tbook, JsonRequestBehavior.AllowGet);
        }

My Html View
<input class="form-control" id="Day" type="text" placeholder="Day" style="width: 94px;">
<input class="form-control" id="Month" type="text" placeholder="Month" style="width: 94px;">
<input class="form-control" id="Year" type="text" placeholder="Year" style="width: 94px;">

My Binding Function
function bindcontrol(data) {
            $.each(data, function (key, value) {
                $("#mymodal").modal('show');
                if (value == true || value == false) {
                    $("#addform").find("input[type='checkbox'][name='" + key + "']").prop("checked", value);
                }
                else {
                    $("#addform").find("input[name='" + key + "']").val(value);
                    $("#addform").find("textarea[name='" + key + "']").val(value);
                    $("#addform").find("select[name='" + key + "']").val(value);
                }
            })
        }

A: Please check this link
ASP.NET MVC JsonResult Date Format
Or if you want to perform server-side
https://www.developer.com/net/dealing-with-json-dates-in-asp.net-mvc.html
function ToJavaScriptDate(value) {
  var pattern = /Date\(([^)]+)\)/;
  var results = pattern.exec(value);
  var dt = new Date(parseFloat(results[1]));
  return (dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear();
}

function bindcontrol(data)
{
    $.each(data, function (key, value)
    {
        $("#mymodal").modal('show');
        if (value == true || value == false) {
            $("#addform").find("input[type='checkbox'][name='" + key + "']").prop("checked", value);
        }
        else
        {
           if(key =="date") // here you date filed
           {
             $("#addform").find("input[name='" + key + "']").val(ToJavaScriptDate(value));
           }
           else
           {
               $("#addform").find("input[name='" + key + "']").val(value);
           }

            $("#addform").find("textarea[name='" + key + "']").val(value);
            $("#addform").find("select[name='" + key + "']").val(value);
        }
    });
}

If you want perform above operation server side need to add some class
  with JsonTextWriter

1) Create Json Result class
public class JsonNetResult : JsonResult
{
  public object Data { get; set; }

  public JsonNetResult()
  {
  }
  ...
}

2) Override method in controller level if you perform only controller level either you can create an attribute and register in global file as well as for all controller level.
public override void ExecuteResult(ControllerContext context)
{
  HttpResponseBase response = context.HttpContext.Response;
  response.ContentType = "application/json";
  if (ContentEncoding != null)
    response.ContentEncoding = ContentEncoding;
  if (Data != null)
  {
   JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented };
   JsonSerializer serializer = JsonSerializer.Create(new JsonSerializerSettings());
   serializer.Serialize(writer, Data);
   writer.Flush();
  }
}

3) Controller Method

public JsonNetResult GetOrder(DateTime id)
{
   TB_EnglishBooks tbook = db.TB_EnglishBooks.Where(x => x.ItemID == id).FirstOrDefault();
            return Json(tbook, JsonRequestBehavior.AllowGet);
  return new JsonNetResult() { Data=tbook};
}


text:
Q: Material Colors in Dwarf Fortress The Dwarf Fortress Wiki, while a wonderful help for most of the time, still falls short from time to time, especially in some of the minor articles.
Something I was unable to find conclusive data about was the uniqueness of the various stone / ore / bar colors.
Simply put -- Which stones / alloys / bars / wood (any construction eligible material) provide which color when used as a building material?
It's easy when you're building something small and can use entirely one type of rock, but when you're in the middle of a megaproject and you're aiming for consistency, you don't want to be looking at the item screen wondering whether the batch of newly excavated "Slate" matches the "mica" you've been using up until that point., and it would be nice to have a list to be able to compare to at a glance.
Note: According to this, there should be 16 different categories.

A: The Dwarf Fortress Wiki has since been updated to contain a dedicated page for this exact purpose.
Click for the full Table

A: I'll break it down for you:

*

*White: Alabaster, Aluminum, Alunite, Borax, Calcite, Chalk, Cryolite, Dolomite, Featherwood, Galena, Silver, Limestone, Marble, Marcasite, Periclase, Platinum, Quartzite, Rock salt, Satinspar, Selenite, Stibnite, Talc

*Grey: Anhydrite, Bismuthinite, Dacite, Granite, Phyllite

*Dark Grey: Andesite, Basalt, Bituminous coal, Chromite, Claystone, Diorite, Gabbro, Graphite, Hornblende, Ilmenite, Jet, Lignite, Magnetite, Mica, Obsidian, Pyrolusite, Rhyolite, Shale, Slade, Slate, Sphalerite, Tetrahedrite

*Cyan: Adamantine, Ice, Microcline

*Dark Cyan: Lay Pewter, Clear Glass

*Blue: Cobaltite

*Dark Blue:  Kimberlite

*Purple: Pitchblende, Rutile

*Dark Red: Bauxite, Hematite, Kaolinite

*Red: Cinnabar, Petrified wood, Realgar

*Yellow: Brimstone, Gold, Gypsum, Orpiment, Orthoclase, Saltpeter, Sylvite

*Dark Yellow: Cassiterite, Chert, Conglomerate, Copper, Puddingstone, Sandstone, Schist, Siltstone

*Green: Malachite, Olivine, Serpentine

*Light Green: Garnierite

Please note: there are no Black, Dark Cyan, Light Blue or Light Purple stones, though they are 4 of the 16 possible colors. You can get some of these colors via alternative means, such as wood, ore, metal alloys, or glass.
Data compiled from here