text:
Q: Flickering effect when hovering title. Title over opacity background Having this html:
<!DOCTYPE html>

    <title>Image hover</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width">

            TITLESubtitle

I get almost what I want. When I hover the area I get opacity 0.4 background with a title above, but when I hover the title/subtitle I get a "flickering effect".I dont want this "flickering effect". How do I get rid of that? (I'm quite sure it's this:
.gecoitems .gecoitem.wrapper-title.hover:hover + .title.hover {display:block;} that's the issue but how do I solve this? I don't want anything top happen when I hover the title (just want the opacity 0.4 to "stay there")
A JS Fiddle to explain further: https://jsfiddle.net/1rLzeht9/

A: You can try the following snippet, I changed some of the display:block to opacity:1, and added a z-index property to the .title
Also I moved your css, got rid of the body, meta etc tags for the purpose of this snippet

.gecoitems {
  list-style-type: none !important;
  margin: 0 auto !important;
  width: 1200px;
}
.gecoitems .gecoitem {
  margin-bottom: 20px;
  display: block;
}
.gecoitems .column {
  float: left;
}
.gecoitems {
  width: 1200px;
}
.gecoitems .gecoitem.normal {
  width: 1200px;
  height: 252px;
  background: #006505;
  color: #fff;
}
/* links */

.gecoitems .gecoitem:hover {
  opacity: 1;
}
.image-listitem-wrapper {
  position: relative;
}
.image-listitem-wrapper .title {
  position: absolute;
  top: 40%;
  left: 0;
  opacity: 1.0;
  color: #ffffff;
  text-transform: uppercase;
  width: 100%;
  text-align: center;
  font-size: 35px;
  line-height: normal;
  z-index:-1;
}
.image-listitem-wrapper .title.hover {
  opacity: 0;
  color: #000000;
  top: 35%;
}
.image-listitem-wrapper .title.hover .services {
  text-transform: lowercase;
  display: block;
}
.gecoitems .gecoitem.wrapper-title.hover:hover {
  opacity: 0.4;
}
.gecoitems .gecoitem.wrapper-title.hover:hover + .title.hover {
  opacity: 1;
}
.title:hover {
  opacity: 1 !important;
}
.slow-fade {
  opacity: 0.8;
  -webkit-transition: opacity .25s ease-in-out;
  -moz-transition: opacity .25s ease-in-out;
  -o-transition: opacity .25s ease-in-out;
  transition: opacity .25s ease-in-out;
}

        TITLESubtitle

You may also add pointer-events:none to the .title element, see This Fiddle. This removes the title being the target of mouse events

A: Your problem is that since .title.hover is not inside .wrapper-title you lose the :hover selector when the mouse goes over .title, therefore the element is hiden, bringing again the hover to the wrapper, and so on.
You can avoid that by setting pointer-events: none to the title.
https://developer.mozilla.org/es/docs/Web/CSS/pointer-events


text: Q: Load React/Angular/Vue result page content to C# backend variable Is it possible to load html of complete page, which content generates by JS-code? For example load page content with any JS-frameworks like React or Angular into C# backend variable? Previously I used HttpClient, but it loads initial page content, withot JS changes. How to get complete content of page in backend code?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rigorous definition of a function whose input is a set Assume we have an $f: \mathbb A \rightarrow \mathbb R^{n}  $ with $ \mathbb A \subseteq \mathbb R^{m} $. Some authors, in order to write down the set of outputs for a given set of inputs, say $ P $,  write $f(P)$. I guess what they mean is:
$$ f(P) = \{ z\in\mathbb R^{n}|z=f(x) \ for \ x\in P\} $$
But is that really allowed? The inputs of $f$ should only be members of $\mathbb A $, not entire sets. It seems to me as a symbolic notation. Is there something more rigorous out there? (something that might involve a set function maybe ?)

A: In most circumstances, we make this definition and it causes no problems.
But in some circumstances, you want to distinguish these two things.  If $f : X \to Y$ is a function, you may defined an "induced function" connecting the power sets $ f^* : \mathcal{P}(X) \to \mathcal{P}(Y)$.


text:
Q: cant redirect rsync error to stdout Hi everyone the following works fine
rsync -r -e "ssh -i /key/file.ssh/" name@server.org:/remote/place /local/place/

but the following
rsync -r -e "ssh -i /key/file.ssh/" name@server.org:/remote/place /local/place/ 2>&1 /some/local/place/log.txt

produces
Unexpected local arg: /rds/PRJ-InsulinAnalogs/gadi_backup/
If arg is a remote file/dir, prefix it with a colon (:).
rsync error: syntax or usage error (code 1) at main.c(1215) [receiver=3.0.6]


text:
Q: Receiving same message multiple times through Subscription IBM MQ Only in one of the subscription message listener is getting same message multiple times. I am using weblogic server and using Ejb.
I am using a durable subscription. I have tried SHARED and CLONED both but separately and still the issue is same
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
    @ActivationConfigProperty(propertyName = "subscriptionDurability", propertyValue = "Durable"),
    @ActivationConfigProperty(propertyName = "subscriptionName", propertyValue = ""),
    @ActivationConfigProperty(propertyName = "sharedSubscription", propertyValue = "TRUE")
   })

CLONED
    @ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Topic"),
    @ActivationConfigProperty(propertyName = "subscriptionDurability", propertyValue = "Durable"),
    @ActivationConfigProperty(propertyName = "subscriptionName", propertyValue = ""),
    @ActivationConfigProperty(propertyName = "cloneSupport", propertyValue = "ENABLED"),

So i am using Abstarct Class which implemant message listener
    public void onMessage(Message message) {
    LOGGER.info("Receive Host message: {}", message);

I parse the message and then in some different method I sendACK
protected void createAndSendAckMessage(String msgToSend, Message request) throws JMSException {
    Connection connection = null;
    Session session = null;
    MessageProducer producer = null;

    try {
        connection = getConnectionFactory().createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

In a different MDB which a subscriber I extend that abstract class and define all the @ActivationConfigProperty
I am creating a .binding file to specify port, Host, qmanager and topics information


text:
Q: How do i install ubuntu on corrupt win 7 I have an assembled computer. It runs on Windows 7 Ultimate. I exactly don't know what  happened but when I switch it on , it says  that "the file checksum does not match the computed checksum".

So I thought of installing Ubuntu in it.But it is not happening. I burned the Ubuntu downloaded files on a DVD RW.
I set it to boot using the disc but it said "Reboot and select proper boot device or insert boot media in selected boot device and press a key". I did what I can, but I am unable to boot it.
I need a little help ASAP.

A: There are two separate problems here:

*

*Does the DVD now contain a bootable Ubuntu installer. (check how you created the DVD). You need a bootloader from somewhere.

*How can you select the DVD drive, to boot from. (see below)

You need to get the PC to select the correct boot source (your DVD drive).
Best method is MANUAL, not setting boot order.
You need to select whatever key (often Esc, or F10) to see BIOS menu. Then select 'manually select boot device' (or similar).
If you identify the exact motherboard, BIOS, etc. someone can probably tell you exact steps.

Then follow steps as suggested by @Registered User.


text:
Q: Google OAuth for standalone web app errors with disallowed_useragent Up until recently, I had a standalone web app (e.g. Add to Homescreen) successfully authenticating users with Google's OAuth. Apparently they recently made changes and are not going to allow native web-views to initiate OAuth flows. This is problematic. Of course, I had an app set up in the developer console that was authorized to do this but in my futzing around I accidentally deleted it before realizing this change had happened.
How can I use Google OAuth within a standalone web app?

A: my tests suggest that if you use a google client id from a project created months ago you get a warning about this only working until april 2017, and if you create a new google project you get disallowed_useragent instead. so if you had another thing you created a google project for try borrowing a client id from there...

A: In the end, I was never able to find an old project with an ID that would work. So I had to get creative. Instead of asking users to "add to homescreen" as step 1, I ask them to sign in first. Then, I take them to a page who's URL works once to sign them in (they're account is empty and my app doesn't send emails, so the security risk is nominal). The URL they end up adding to their homescreen signs them in the first time it's used.
To try it out, try signing up for While, a to-do list app, on an iPhone.


text:
Q: Catel IUIViusalizerService ShowDialog() error I'm having troubles with trying to show a dialog. The IUIViusalizerService ShowDialog() method produces following error:
The error: "Method 'Show' not found on 'MyView'
The debugger runs to UIVisualizerService.cs to the method below (beginning on line 380 in the cs file):
protected virtual bool? ShowWindow(FrameworkElement window, bool showModal)
{
        if (showModal)
        {
            var showDialogMethodInfo = window.GetType().GetMethodEx("ShowDialog");
            if (showDialogMethodInfo != null)
            {
                // Child window does not have a ShowDialog, so not null is allowed
                return showDialogMethodInfo.Invoke(window, null) as bool?;
            }

            Log.Warning("Method 'ShowDialog' not found on '{0}', falling back to 'Show'", window.GetType().Name);
        }

        var showMethodInfo = window.GetType().GetMethodEx("Show");
        if (showMethodInfo == null)
        {
            string error = string.Format("Method 'Show' not found on '{0}', cannot show the window", window.GetType().Name);
            Log.Error(error);

            throw new NotSupportedException(error);
        }

       showMethodInfo.Invoke(window, null);
       return null;
    }

My calling code:
public MainWindowViewModel()
    {
        ViewModels.MyViewModel mv = new MyViewModel();

        var ui = GetService<IUIVisualizerService>();
        ui.ShowDialog(mv)
    }

Questions:
    1. Am I supposed to impliment a "Show()" method in code behind?
    2. Is there a different base class for a DialogView and/or DialogViewModel that must be used?
I started having this problem with Catel 3.6
Thank You

A: Make sure that the view model that you use resolves to a view that derives from DataWindow or a custom Window with the Catel WindowLogic implemented as shown in the documentation.


text:
Q: How to dynamically display different components type based on runtime constraints in Angular2+? I have a grid component and a dynamically determined second component.
There is a splitter component that always contains a grid in the top part.
A secondary component will be displayed in the bottom part of the splitter.
The type of secondary component will depend on the selected row type in the grid.
Select row 1 and the secondary component might be line chart
Select row 2 and the secondary component might be another grid...
As the user changes the selected row, the component and the data displayed will need updating.
Any ideas on how to set this up?

A: You can dynamically load second component with [ngSwitch] directive.
If you want to dynamically load them, build a code similar to this
<div [ngSwitch]="variable">
    <app-first *ngSwitchCase="1"></app-first>
    <app-second *ngSwitchCase="2"></app-second>
</div>

It's up to you how you will determine which component should be loaded. You can for example change value of a variable with jQuery of plain JavaScript to render specific component. Component will be automatically updated if you change a row.
If you want to automatically update content so the data from 1st component matches 2nd, you have to use some cross component communication provided by Angular4.
Good explanation how to do this here: https://www.youtube.com/watch?v=I317BhehZKM


text:
Q: In a DataTable object, how do I store an array of strings in each cell of a specific column? For example, if each row of the data table holds information about an employee, one column might hold a string for their names, one column might hold a string for their phone numbers, and one column might be for their tasks. If an employee has multiple tasks, how can I store an array of strings that represents each task in that particular data cell?

A: You could use string.Join() on your array, and specify the delimiter to use between each array entry.
When you read it back out you can then split it back into an array.
Here is a quick and dirty bit of code that shows how to do it:
var tasks = new[] {"Boss", "Secretary", "Tea Lady"};

var joined = string.Join(", ", tasks);

var splitAgain = joined.Split(new[]{", "}, StringSplitOptions.RemoveEmptyEntries);

A: If you really need to use DataTable I would either combine multiple DataTables into a DataSet... or store this in xml format in a column


text:
Q: Nokogiri get element which attribute match a pattern I'm trying to guess price from an HTML.
If #id or .class or direct parent has attribute value like some regex =~ [price.*|prdown|proff]+
1) Does Nokogiri doc.css accept regex like jsoup Java library does? i.e. [attr~=regex] https://jsoup.org/apidocs/org/jsoup/select/Selector.html
2) Can I accomplish that passing regex as argument for the attribute value? instead of creating a custom function?
doc = Nokogiri::HTML(open(url).read)

  def get_price(doc)
    if doc.at_css("meta[itemprop='price']")
      price = doc.css("meta[itemprop='price']").first.attributes["content"]
    elsif doc.at_css('.price')
      price = doc.at_css('[class~=price]').text
    else
     price = ''
    end
    /([\d|\.|\$]+)/.match(price)[1].gsub(/[\.|\$]+/, '')
  end

A: Yes, Nokogiri has provision for you to create your own search, css, xpath, at, at_css or at_xpath functions.
It's in the Nokogiri::XML::Node and Nokogiri::XML::Searchable documentation. For instance:

Custom XPath functions and CSS pseudo-selectors may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching NodeSet. Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example:

node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")'
  Class.new {
    def regex node_set, regex
      node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ }
    end
  }.new
)


text:
Q: SSIS define EOL (or row delimiter) This is a silly question but it is driving me nuts: why can't I define row delimiters in SSIS, just HEADER delimiters? Here is my situation: my file contains records of varying sizes:

So, I am unable to define a row delimiter for my file. Further, I'm also unable to define the total row size (I am ASSUMING here that SSIS just adds up the column lengths defined in order to derive a total row length, but indeed there exists no independent one).
Here are all the settings available:

And as a result I am getting sparsely populated records (because the rows do not end where they should):

Thank you so much in advance!

A: When your text file format is all fixed-width except for the last (right-most) column, you should use the Ragged Right format.  It lets you specify widths for all columns except the last one, which uses the row delimiter instead.


text:
Q: Not sure why my program will not execute I am trying to finish my homework and having the hardest time trying to figure out why my program will not execute what i want ti to print.  Can anyone look at what i have so far and tell me where i am going wrong.
def main ():
last_name = input("Enter last name: ')
first_name = input("Enter first name: ')
print("last name"',',"first name")
main()

A: 1. Indentation
Some of your code needs to go inside your function definition for main, which we can do by indenting it.
def main ():
    last_name = input("Enter last name: ')   # \
    first_name = input("Enter first name: ') #  |-- This is the content of "main"
    print("last name"',',"first name")       # /
main()                                       # This causes "main" to run

2. Quotation Marks
Your opening and closing marks need to be the same; they should either be both " or both '.
def main ():
    last_name = input("Enter last name: ")
    first_name = input("Enter first name: ")
    print("last name"',',"first name")
main()

3. Printing
You're trying to print the value of the last_name variable, then a comma, then the value of the first_name variable. You've made a good effort, but your syntax is off. You need commas in-between each string you want to print, but these commas should not be in quotes, because they're syntax, not a string. The same applies to your variable names - if you put them in quotes, Python interprets them as text, but that isn't what we want - we want their values.
When your code is changed to fix these issues, this is the result:
def main ():
    last_name = input("Enter last name: ")
    first_name = input("Enter first name: ")
    print(last_name, ",", first_name)
main()

A: In input("Enter last name: ') (and other parts of your code), your "string starter" and "string ender" (in this case, " and ' are not the same characters). You should use the same character.
Also, your function code is not properly indented.
You're also printing "last name" as a string and not as the variable.
An example of printing a variable using the print() method would be:
# what you want to do
> a = "test"
> print(a)
test

# what you did
> a = "test"
> print("a")
a

You're also not concatenating your strings properly. You can use the + operator to concatenate strings in Python (you can also do this in your print() function!)

A: This is what it could look like:
def main ():
    first_name = input("Enter first name: ")
    last_name = input("Enter last name: ")
    print(last_name + ", " + first_name)
main()

*

*Either use double (") or single (') quotes.

*Indent your code properly.

*In your print call, pass the variables correctly.


text:
Q: ¿Cómo trabajar con JSON en Java? Tengo la siguiente petición URL, esta me devuelve un JSON.
Realizo la petición en Java de la siguiente manera:
class Main {
  public static void main(String[] args) throws Exception {
    final String uri = "https://api.weather.gov/gridpoints/TOP/31,80/forecast";

    OkHttpClient cliente = new OkHttpClient();
    Request request = new Request.Builder().url(uri).build();

    try {
      Response response = cliente.newCall(request).execute();
      System.out.println("Codigo de respuesta: " + response.code());
      if (response.isSuccessful()) {
        String data = response.body().string();
        System.out.println(data);
      }
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
  }
}

Obtengo el JSON completo en String. Pero necesito este array de la respuesta:
"periods": [
{
"number": 1,
"name": "Tonight",
"startTime": "2021-10-09T20:00:00-05:00",
"endTime": "2021-10-10T06:00:00-05:00",
"isDaytime": false,
"temperature": 58,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 10 mph",
"windDirection": "W",
"icon": "https://api.weather.gov/icons/land/night/ovc?size=medium",
"shortForecast": "Cloudy",
"detailedForecast": "Cloudy, with a low around 58. West wind 5 to 10 mph."
},
{
"number": 2,
"name": "Sunday",
"startTime": "2021-10-10T06:00:00-05:00",
"endTime": "2021-10-10T18:00:00-05:00",
"isDaytime": true,
"temperature": 71,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 15 mph",
"windDirection": "NW",
"icon": "https://api.weather.gov/icons/land/day/rain_showers,20/rain_showers,40?size=medium",
"shortForecast": "Chance Rain Showers",
"detailedForecast": "A chance of rain showers after 7am. Cloudy, with a high near 71. Northwest wind 5 to 15 mph. Chance of precipitation is 40%."
},
{
"number": 3,
"name": "Sunday Night",
"startTime": "2021-10-10T18:00:00-05:00",
"endTime": "2021-10-11T06:00:00-05:00",
"isDaytime": false,
"temperature": 50,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 mph",
"windDirection": "W",
"icon": "https://api.weather.gov/icons/land/night/rain_showers,40?size=medium",
"shortForecast": "Chance Rain Showers",
"detailedForecast": "A chance of rain showers. Mostly cloudy, with a low around 50. West wind around 5 mph. Chance of precipitation is 40%."
},
{
"number": 4,
"name": "Columbus Day",
"startTime": "2021-10-11T06:00:00-05:00",
"endTime": "2021-10-11T18:00:00-05:00",
"isDaytime": true,
"temperature": 71,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 10 mph",
"windDirection": "NW",
"icon": "https://api.weather.gov/icons/land/day/rain_showers,20/sct?size=medium",
"shortForecast": "Slight Chance Rain Showers then Mostly Sunny",
"detailedForecast": "A slight chance of rain showers before 7am. Mostly sunny, with a high near 71. Northwest wind 5 to 10 mph. Chance of precipitation is 20%."
},
{
"number": 5,
"name": "Monday Night",
"startTime": "2021-10-11T18:00:00-05:00",
"endTime": "2021-10-12T06:00:00-05:00",
"isDaytime": false,
"temperature": 47,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 mph",
"windDirection": "S",
"icon": "https://api.weather.gov/icons/land/night/few?size=medium",
"shortForecast": "Mostly Clear",
"detailedForecast": "Mostly clear, with a low around 47. South wind around 5 mph."
},
{
"number": 6,
"name": "Tuesday",
"startTime": "2021-10-12T06:00:00-05:00",
"endTime": "2021-10-12T18:00:00-05:00",
"isDaytime": true,
"temperature": 74,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 15 mph",
"windDirection": "SE",
"icon": "https://api.weather.gov/icons/land/day/few?size=medium",
"shortForecast": "Sunny",
"detailedForecast": "Sunny, with a high near 74. Southeast wind 5 to 15 mph, with gusts as high as 25 mph."
},
{
"number": 7,
"name": "Tuesday Night",
"startTime": "2021-10-12T18:00:00-05:00",
"endTime": "2021-10-13T06:00:00-05:00",
"isDaytime": false,
"temperature": 57,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "15 mph",
"windDirection": "SE",
"icon": "https://api.weather.gov/icons/land/night/tsra_sct,30/tsra_sct,80?size=medium",
"shortForecast": "Chance Showers And Thunderstorms",
"detailedForecast": "A chance of showers and thunderstorms between 7pm and 1am, then showers and thunderstorms. Mostly cloudy, with a low around 57. Southeast wind around 15 mph, with gusts as high as 30 mph. Chance of precipitation is 80%."
},
{
"number": 8,
"name": "Wednesday",
"startTime": "2021-10-13T06:00:00-05:00",
"endTime": "2021-10-13T18:00:00-05:00",
"isDaytime": true,
"temperature": 69,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "15 to 20 mph",
"windDirection": "SW",
"icon": "https://api.weather.gov/icons/land/day/tsra_hi,80/tsra_hi,50?size=medium",
"shortForecast": "Showers And Thunderstorms",
"detailedForecast": "Showers and thunderstorms before 1pm. Mostly sunny, with a high near 69. Southwest wind 15 to 20 mph, with gusts as high as 30 mph. Chance of precipitation is 80%."
},
{
"number": 9,
"name": "Wednesday Night",
"startTime": "2021-10-13T18:00:00-05:00",
"endTime": "2021-10-14T06:00:00-05:00",
"isDaytime": false,
"temperature": 43,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 15 mph",
"windDirection": "W",
"icon": "https://api.weather.gov/icons/land/night/few?size=medium",
"shortForecast": "Mostly Clear",
"detailedForecast": "Mostly clear, with a low around 43. West wind 5 to 15 mph, with gusts as high as 25 mph."
},
{
"number": 10,
"name": "Thursday",
"startTime": "2021-10-14T06:00:00-05:00",
"endTime": "2021-10-14T18:00:00-05:00",
"isDaytime": true,
"temperature": 65,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 10 mph",
"windDirection": "N",
"icon": "https://api.weather.gov/icons/land/day/few?size=medium",
"shortForecast": "Sunny",
"detailedForecast": "Sunny, with a high near 65."
},
{
"number": 11,
"name": "Thursday Night",
"startTime": "2021-10-14T18:00:00-05:00",
"endTime": "2021-10-15T06:00:00-05:00",
"isDaytime": false,
"temperature": 44,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 10 mph",
"windDirection": "N",
"icon": "https://api.weather.gov/icons/land/night/sct?size=medium",
"shortForecast": "Partly Cloudy",
"detailedForecast": "Partly cloudy, with a low around 44."
},
{
"number": 12,
"name": "Friday",
"startTime": "2021-10-15T06:00:00-05:00",
"endTime": "2021-10-15T18:00:00-05:00",
"isDaytime": true,
"temperature": 59,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "10 to 15 mph",
"windDirection": "N",
"icon": "https://api.weather.gov/icons/land/day/sct?size=medium",
"shortForecast": "Mostly Sunny",
"detailedForecast": "Mostly sunny, with a high near 59."
},
{
"number": 13,
"name": "Friday Night",
"startTime": "2021-10-15T18:00:00-05:00",
"endTime": "2021-10-16T06:00:00-05:00",
"isDaytime": false,
"temperature": 40,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 10 mph",
"windDirection": "NW",
"icon": "https://api.weather.gov/icons/land/night/few?size=medium",
"shortForecast": "Mostly Clear",
"detailedForecast": "Mostly clear, with a low around 40."
},
{
"number": 14,
"name": "Saturday",
"startTime": "2021-10-16T06:00:00-05:00",
"endTime": "2021-10-16T18:00:00-05:00",
"isDaytime": true,
"temperature": 62,
"temperatureUnit": "F",
"temperatureTrend": null,
"windSpeed": "5 to 10 mph",
"windDirection": "NW",
"icon": "https://api.weather.gov/icons/land/day/few?size=medium",
"shortForecast": "Sunny",
"detailedForecast": "Sunny, with a high near 62."
}
]

Necesito rescatar ese array de la respuesta convertirlo en un Objeto List<> para recorrer y aplicar filtros según las fechas. Primera vez que me toca trabajar en Java con HTTP solicitudes y JSON. No sé que librerías son buenas o de que manera filtrar el JSON para obtener solo ciertos parametros y no todo el objeto.

A: Ya he encontrado la solución con ayuda de la librería de Google GSON.
Primero necesite crear una clase en Java con las propiedades que contendrá el JSON que recibiré de la petición.
En este caso tengo dos clases, una que es el objeto completo el cual llamé Forecast.java que contendrá las propiedades que devuelve el request a la API. Utilizando la librería de Google puedo declarar que será de tipo JsonArray o JsonObject.
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class Forecast {

    JsonArray context;
    String type;
    JsonObject geometry;
    JsonObject properties;

    public JsonArray getContext() {
        return context;
    }

    public final void setContext(JsonArray context) {
        this.context = context;
    }

    public String getType() {
        return type;
    }

    public final void setType(String type) {
        this.type = type;
    }

    public JsonObject getGeometry() {
        return geometry;
    }

    public final void setGeometry(JsonObject geometry) {
        this.geometry = geometry;
    }

    public JsonObject getProperties() {
        return properties;
    }

    public final void setProperties(JsonObject properties) {
        this.properties = properties;
    }

    public Forecast() {
        setContext(new JsonArray());
        setType("");
        setGeometry(new JsonObject());
        setProperties(new JsonObject());
    }

    public Forecast(JsonArray context, String type, JsonObject geometry, JsonObject properties) {
        setContext(context);
        setType(type);
        setGeometry(geometry);
        setProperties(properties);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Forecast{context=").append(getContext());
        sb.append(", type=").append(getType());
        sb.append(", geometry=").append(getGeometry());
        sb.append(", properties=").append(getProperties());
        sb.append('}');
        return sb.toString();
    }

Y la clase Period, la cual contendrá todos los objetos del array periods que contiene el JSON, que es en realidad el que necesito para obtener la predicción de los próximos 3 días.
public final class Period {

    private int number;
    private String name;
    private Date startTime;
    private Date endTime;
    private boolean isDayTime;
    private int temperature;
    private String temperatureUnit;
    private String temperatureTrend;
    private String windSpeed;
    private String windDirection;
    private String icon;
    private String shortForecast;
    private String detailedForecast;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getStartTime() {
        return startTime;
    }

    public void setStartTime(Date startTime) {
        this.startTime = startTime;
    }

    public Date getEndTime() {
        return endTime;
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
    }

    public boolean isIsDayTime() {
        return isDayTime;
    }

    public void setIsDayTime(boolean isDayTime) {
        this.isDayTime = isDayTime;
    }

    public int getTemperature() {
        return temperature;
    }

    public void setTemperature(int temperature) {
        this.temperature = temperature;
    }

    public String getTemperatureUnit() {
        return temperatureUnit;
    }

    public void setTemperatureUnit(String temperatureUnit) {
        this.temperatureUnit = temperatureUnit;
    }

    public String getTemperatureTrend() {
        return temperatureTrend;
    }

    public void setTemperatureTrend(String temperatureTrend) {
        this.temperatureTrend = temperatureTrend;
    }

    public String getWindSpeed() {
        return windSpeed;
    }

    public void setWindSpeed(String windSpeed) {
        this.windSpeed = windSpeed;
    }

    public String getWindDirection() {
        return windDirection;
    }

    public void setWindDirection(String windDirection) {
        this.windDirection = windDirection;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public String getShortForecast() {
        return shortForecast;
    }

    public void setShortForecast(String shortForecast) {
        this.shortForecast = shortForecast;
    }

    public String getDetailedForecast() {
        return detailedForecast;
    }

    public void setDetailedForecast(String detailedForecast) {
        this.detailedForecast = detailedForecast;
    }

    public Period() {
        this.number = 0;
        this.name = "";
        this.startTime = new Date();
        this.endTime = new Date();
        this.isDayTime = true;
        this.temperature = 58;
        this.temperatureUnit = "F";
        this.temperatureTrend = null;
        this.windSpeed = "";
        this.windDirection = "NW";
        this.icon = "";
        this.shortForecast = "";
        this.detailedForecast = "";
    }

    public Period(int number, String name, Date startTime, Date endTime, boolean isDayTime, int temperature, String temperatureUnit, String temperatureTrend, String windSpeed, String windDirection, String icon, String shortForecast, String detailedForecast) {
        setNumber(number);
        setName(name);
        setStartTime(startTime);
        setEndTime(endTime);
        setIsDayTime(isDayTime);
        setTemperature(temperature);
        setTemperatureUnit(temperatureUnit);
        setTemperatureTrend(temperatureTrend);
        setWindSpeed(windSpeed);
        setWindDirection(windDirection);
        setIcon(icon);
        setShortForecast(shortForecast);
        setDetailedForecast(detailedForecast);
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("Period{number=").append(getNumber());
        sb.append(", name=").append(getName());
        sb.append(", startTime=").append(getStartTime());
        sb.append(", endTime=").append(getEndTime());
        sb.append(", isDayTime=").append(isIsDayTime());
        sb.append(", temperature=").append(getTemperature());
        sb.append(", temperatureUnit=").append(getTemperatureUnit());
        sb.append(", temperatureTrend=").append(getTemperatureTrend());
        sb.append(", windSpeed=").append(getWindSpeed());
        sb.append(", windDirection=").append(getWindDirection());
        sb.append(", icon=").append(getIcon());
        sb.append(", shortForecast=").append(getShortForecast());
        sb.append(", detailedForecast=").append(getDetailedForecast());
        sb.append('}');
        return sb.toString();
    }

Una vez que tenemos los modelos listos para recibir los datos, realize la solicitud mediante la siguiente función que recibe los grados de longitud y latitud de la locación.
public static void peticionHttpGet(int longitud, int latitud) throws Exception {
        StringBuilder resultado = new StringBuilder();
        URL url = new URL("https://api.weather.gov/gridpoints/TOP/" + longitud + "," + latitud + "/forecast");
        HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
        conexion.setRequestMethod("GET");
        try (BufferedReader rd = new BufferedReader(new InputStreamReader(conexion.getInputStream()))) {
            String linea;
            while ((linea = rd.readLine()) != null) {
                resultado.append(linea);
            }
        }
        Gson data = new Gson();
        Forecast f = data.fromJson(resultado.toString(), Forecast.class);
        int cont = 0;
        Date fechaActual = new Date();
        for (JsonElement jsonElement : f.getProperties().getAsJsonArray("periods")) {
            Period p = data.fromJson(jsonElement.getAsJsonObject(), Period.class);
            if (p.isIsDayTime()) {
                if (Functions.calcularProximosDias(p.getStartTime(), fechaActual)) {
                    System.out.println("La temperatura para el día "
                            + p.getStartTime()
                            + " será de "
                            + Functions.parseToCelsius(p.getTemperature())
                            + " ° Celsius");
                    fechaActual = p.getStartTime();
                    cont++;
                    if (cont == 3) {
                        break;
                    }
                }
            }
        }
    }

Este método ejecuta toda la lógica que requiere la función y muestra en consola el pronóstico para los proximos 3 días. Lo que quiero destacar de esta función, es la librería GSON, que me permite crear un objeto de clase mediante un JSON y así poder acceder a todas sus propiedades.
Gson data = new Gson();
Forecast f = data.fromJson(resultado.toString(), Forecast.class);

Estás simples lineas generan una clase GSON que contiene las funciones que permiten trabajar con objetos json. Mediante el método from.Json() este método recibe un objeto JSON, en este caso recibe el resultado de la solicitud HTTP y como segundo argumento, la clase con el tipo. Esto ya crea una instancia del objeto como una clase y podemos acceder a las propiedades con los accesadores propios de la clase. (Esto es increíblemente fácil y efectivo).
Luego como mencione yo necesitaba acceder a la propiedad con clave "periods" del objeto JSON (un array con los pronosticos); Entonces para esto, lo único que debo hacer es utilizar la siguiente línea:
f.getProperties().getAsJsonArray("periods")

Y el resultado que obtengo es el array con los pronosticos de los proximos días. Ya simplemente queda aplicar la lógica necesaria.
Me sorprendió la facilidad de esta librería desarrollada por Google, desde hoy se convierte en mi librería favorita en cuanto a objetos JSON. Me parece muy facil trabajar, sobre todo que siempre he trabajado con patrones de arquitectura MVC y REST orientada a objetos.

A: Justo este tema a mi se me complico un poco, el manejo de objetos JSON, ¿que te recomiedo? Utilizar la Api Gson de Java ya que es muy
sencilla y fácil de implementar.
Te dejo un post sobre el Asunto.https://jarroba.com/gson-json-java-ejemplos/


text:
Q: Change all Off Sheet connectors to Ports I´m new to Altium Designer. It seems like AD can´t use Off Sheet Connectors for hierarchical design, so I want to change all Off Sheet Connectors to Ports.
Is there an easy way to do this? Btw: There are a lot of Off Sheet Connectors in the design.
How can I use NetLabels in the hierarchical design? Somehow only Ports appear as Sheet Entries.
Thank you.

A: In Altium Designer ports are used to create sheet entries.
Net labels are used to connect wires and buses inside a sheet only.
The power supply symbols (GND, VDD etc) are common over multiple sheets, so you don't need to make ports for them (although you can if you want it for clarity).
I don't think you can easily change the off-sheet connectors into a port, so you need to place a new port and give it the right name.
Altium documentation states the use of off-sheet symbols only for a specific reason:

Multiple sub-sheets may be referenced by a single sheet symbol. Separate each filename by a semi-colon in the Filename field. With the effective use of off-sheet connectors placed on the sub-sheets, you can effectively spread a section of your design over multiple sheets, treated as though they were one giant (flat) sheet. Note however, that use of off-sheet connectors is only possible for sheets referenced by the same sheet symbol.

A: I would beg to differ with the answers posted here, but Altium absolutely has the ability to do what you're trying to do.
Because people sometimes use different names than others for the same thing, I'm just going to show a basic example, not necessarily tailored to your question, but you should be able to modify this easily to suit your needs.
The key to the solution is the Smart Paste tool.
Lets say I have a bunch of ports and I'd like to paste them onto nets of the same name.  Simply select and Copy.

Click Edit -> Smart Paste
Here I chose paste as net labels and wires:

The final result:

As you can see from the second image, you can paste as Ports, Net Labels, even as Sheet entries where you can paste them onto a hierarchy.
This is very useful for connecting say a connector block up to a new hierarchy with a large number of nets.  For example, from the same original Copied material, I pasted this onto a sheet symbol.

I trust you can modify this to suit your original question.

A: If my memory serves, off-sheet connectors were really only included in Altium Designer for backwards-compatibility with older versions of the software (Protel). I generally use global net names instead.
As for changing off-sheet connectors to ports, I don't believe Altium currently has a good way to do that. I think you'd have to go through them one-by-one to replace them with ports. I ran into this a few months ago at work -- an old design used off-sheet symbols but we needed to change them to ports for use in a hierarchical schematic. We ended up having to go through and replacing them manually. It would be nice if Altium would allow the "Object Kind" to be changed in the Schematic Inspector.
EDIT: I tested Joel's answer and it works beautifully. Please disregard this answer.


text:
Q: What are all the available images within JRE? I need simple icons like gears, arrows and such for my program. Giving away my program without worrying about extra images on the host file system would be nice. I know some images are contained in JRE for Swing, like the yellow warning triangle:

Still, i can not locate the above triangle within the JRE i am using. So i would not know how to use it (except by using  JOptionPane.showMessageDialog(null, "My warning message", "WARNING", JOptionPane.WARNING_MESSAGE);

A: These images are bundled with the standard library class files, within a big "modules" file in your JDK directory. See here: How to extract the file jre-9/lib/modules?
This warning.png image in particular is stored as javax/swing/plaf/metal/icons/ocean/warning.png within that modules file. You can see a list of all the "ocean" theme icons in OpenJDK source here:  https://github.com/openjdk/jdk/tree/master/src/java.desktop/share/classes/javax/swing/plaf/metal/icons/ocean

A: Consider using Unicode characters, instead of images.  For gear, try using "\u2699", "\u26ed", or "\u26ee".  For arrows, there are entire blocks in Unicode: Arrows; Supplemental Arrows-A, -B, and -C; and Miscellaneous Symbols and Arrows.  There are many symbol blocks, like Miscellaneous Symbols, Dingbats, Geometric Shapes, and Miscellaneous Symbols and Pictographs.  A nice benefit of using characters is that they scale quite well.
If you must have the JOptionPane icons, you can retrieve them using their corresponding defaults keys:
import java.awt.*;
import javax.swing.*;

public class JOptionPaneIconDisplayer {
    static void show() {
        Icon info = UIManager.getIcon("OptionPane.informationIcon");
        Icon warning = UIManager.getIcon("OptionPane.warningIcon");
        Icon error = UIManager.getIcon("OptionPane.errorIcon");
        Icon question = UIManager.getIcon("OptionPane.questionIcon");

        JPanel panel = new JPanel(new GridLayout(1, 0, 12, 12));
        panel.add(new JLabel(info));
        panel.add(new JLabel(warning));
        panel.add(new JLabel(error));
        panel.add(new JLabel(question));

        panel.setBorder(BorderFactory.createEmptyBorder(24, 24, 24, 24));

        JFrame frame = new JFrame("JOptionPane Icons");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> show());
    }
}

Attempting to read the icons directly from a classpath resource is not a good idea, as their names and locations may change from one Java release to the next.


text:
Q: Allow grid height to change with number of rows (autoheight) I'm implementing a grid in ExtJS 7.0.0 (Modern) and would like the height of the grid to be set to the number of rows that it contains. As you can see from the example on the ExtJS Kitchen Sink the height of the grid is set to 400 and the grid must be scrolled to see the rest of the rows.
Screenshot of the grid that must be scrolled to view all the rows
What I am looking for is to be able to set the height to auto and have the grid height adapt to suit the number of rows in the grid. We have found a way to do this in older versions of ExtJS however I can't find a solution to this for version 7 (Modern).
Can anyone point me in the right direction here?
Take a look at my Sencha Fiddle if you want to have a go.

A: Here is a Fiddle
The key feature is setting grid property scrollable: true
The panel layout is set to vbox.
I set the maxHeight to 400 so the grid will be 400 pixels high but you can not set the maxHeight property and set flex: 1 and the grid will take up all the space vertically that is available and the balance will be scrolltable.
EDIT: New Fiddle Use a vbox layout and set infinite to false on the grid. On your fiddle just remove the height:300 property and add infinite: false

A: *

*Native way:

let grid = Ext.getCmp('example-grid-id'); //get your grid component, there are few ways to do this. "getCmp" is one of those ways
let gridHeightHeader = grid.renderElement.dom.getElementsByClassName("x-headercontainer")[0].offsetHeight;
let gridHeightBody   = 0;
let rows = grid.renderElement.dom.getElementsByClassName("x-listitem");
Array.from(rows).forEach(function(row){
    gridHeightBody+=row.offsetHeight; // in pixel, you can console log here
});
grid.setHeight(gridHeightHeader+gridHeightBody+40); // set new dynamic height of the grid + 40 as additional height

*Sencha Ext JS way:

{
    xtype : "panel", //parent of grid component
    fullscreen: true, //optional
    layout:"fit", //HERE is the key
    items:{
        xtype:'grid',
        // height: you don't need this height prop again :)
    }
}


text:
Q: combine multidimensional array into key based dictionary object I am trying to create a price schema for a product, basing on its color, size and material.
My current way of implementation is to maintain 1 JSON object which contains all the options and trying to generate another JSON object using all possible combination of its options.
For example
var productOption = {
  "color":["red","green","yellow"],
  "size":["S","M","L"],
  "material":["leather","linen"]
}

what I want to create something like follow

[
  {
  "red":{
    "S":{
      "leather":{
        "cost":100,"available":true
        }
      }
    }
  },
  {
  "green":{
    "S":{
      "leather":{
        "cost":100,"available":true
        }
      }
    }
  },
  ....

]

so I can do something like price["red"]["S"]["leather"] to access the price for red color, leather, in small size.
Is there a easy way to do it? either in Javascript or Python.
EDIT:
What if some product only has color and size or color only?
var productOption= { color :[...],size:[...]};

EDIT 2:
I made up following code to solve my issue. If you have any suggestion on how I can improve my code. Please let me know.
// I am using lodash for those underscore signs.
var processPrice = function(){
  price = {};
  var keys = _.keys(_.pick(priceOption,function(value,key){
    return !_.isEmpty(value);
  }));
  if(keys.length>0){
    genMatrix(keys,[],price);
  }
};
var genMatrix = function(keys,options,obj){
  var key = keys[0];
  if(keys.length>1){
    var subKeys = _.compact(keys);
      subKeys.shift();
    _.each(priceOption[key],function(opt){
      var subOption = _.compact(options);
      subOption.push(opt.value);
      obj[opt.value]={};
      genMatrix(subKeys,subOption,obj[opt.value]);
    });
  }else{
    _.each(priceOption[key],function(opt){
      obj[opt.value]={cost: 100, available: true};
    });
  }
};

A: Python version
from itertools import product
result = []
for col, siz, mat in product(*(data["color"], data["size"], data["material"])):
    result.append({col: {siz: {mat: {'available': True, 'cost': 100}}}})
print result

Output
[{'red': {'S': {'leather': {'available': True, 'cost': 100}}}},
 {'red': {'S': {'linen': {'available': True, 'cost': 100}}}},
 {'red': {'M': {'leather': {'available': True, 'cost': 100}}}},
 {'red': {'M': {'linen': {'available': True, 'cost': 100}}}},
 {'red': {'L': {'leather': {'available': True, 'cost': 100}}}},
 {'red': {'L': {'linen': {'available': True, 'cost': 100}}}},
 {'green': {'S': {'leather': {'available': True, 'cost': 100}}}},
 {'green': {'S': {'linen': {'available': True, 'cost': 100}}}},
 {'green': {'M': {'leather': {'available': True, 'cost': 100}}}},
 {'green': {'M': {'linen': {'available': True, 'cost': 100}}}},
 {'green': {'L': {'leather': {'available': True, 'cost': 100}}}},
 {'green': {'L': {'linen': {'available': True, 'cost': 100}}}},
 {'yellow': {'S': {'leather': {'available': True, 'cost': 100}}}},
 {'yellow': {'S': {'linen': {'available': True, 'cost': 100}}}},
 {'yellow': {'M': {'leather': {'available': True, 'cost': 100}}}},
 {'yellow': {'M': {'linen': {'available': True, 'cost': 100}}}},
 {'yellow': {'L': {'leather': {'available': True, 'cost': 100}}}},
 {'yellow': {'L': {'linen': {'available': True, 'cost': 100}}}}]

JavaScript version:
var result = [];

for (var i = 0; i < data["color"].length; i += 1) {
    var color = data["color"][i];
    for (var j = 0; j < data["size"].length; j += 1) {
        var size = data["size"][j];
        for (var k = 0; k < data["material"].length; k += 1) {
            var material = data["material"][k], obj = {};
            obj[color] = {};
            obj[color][size] = {};
            obj[color][size][material] = {cost: 100, available: true};
            result.push(obj);
        }
    }
}
console.log(result);


text:
Q: Google Maps Fusion Table API SQL "LIKE" command not working I'm using Google Maps API to pull data from a Fusion Table based on user input. I trying to use the "LIKE" command to create  a more robust search feature, however anything other than simple where queries (like where x=y or x>y) seems to return every entry or no entry at all from the fusion table.
main.js
function updateMap(layer, tableID) {
    var input = document.getElementById('input').value;
    var newLayer = new google.maps.FusionTablesLayer({
        query: {
            select: 'FULL_ADDRESS',
            from: tableID,
            where: "FULL_ADDRESS LIKE  \'%" + input + "%\' "
        }
    });
    console.log(newLayer);
    layer.setMap(null);//deletes old layer
    newLayer.setMap(map);//sets map to new layer
    LAYER = newLayer;// sets global layer to new layer

}

according to the documentation here and here this should work fine.
index.html
<input id="input" class="controls floating-label" type="text" placeholder="Search by Address or Zip Code">

fusion table entry

000000000000000000| Taylor Road , Birmingham, AL, 36117| 0 |$0.00 $6,800.00 |$0.00 |$0.00 |$1,360.00

2nd field is FULL_ADDRESS
live site
My goal is to use the user input to try to partially match a addresses however, it is not working correctly. Is there something I'm missing?
Thanks!

A: LIKE doesn't appear to work so use MATCHES instead


text:
Q: Gcm iOS, subscribe to topic, error code 3004 I'm trying to subscribe to a gcm topic on iOS.
GCMPubSub.sharedInstance().subscribeWithToken(registrationId, topic: "/topics/mytopic", options: nil) { error in
    print(error.localizedDescription)
}

The operation couldn't be completed. (com.google.gcm error 3004.)
I can't find a documentation for this error code anywhere. I've also read the source code where the errors are defined and it looks like this:
typedef NS_ENUM(NSUInteger, GCMServiceErrorCode) {
  /**
   *  HTTP errors.
   */

  // InvalidRequest -- Some parameters of the request were invalid.
  kGCMServiceErrorCodeInvalidRequest = 0,

  // Auth Error -- GCM couldn't validate request from this client.
  kGCMServiceErrorCodeAuthentication = 1,

  // NoAccess -- InstanceID service cannot be accessed.
  kGCMServiceErrorCodeNoAccess = 2,

  // Timeout -- Request to InstanceID backend timed out.
  kGCMServiceErrorCodeTimeout = 3,

  // Network -- No network available to reach the servers.
  kGCMServiceErrorCodeNetwork = 4,

  // OperationInProgress -- Another similar operation in progress,
  // bailing this one.
  kGCMServiceErrorCodeOperationInProgress = 5,

  // Unknown error.
  kGCMServiceErrorCodeUnknown = 7,

  /**
   *  Upstream Send errors
   */

  // Upstream send not available (e.g. network issues)
  kGCMServiceErrorCodeUpstreamServiceNotAvailable = 1001,

  // Invalid send parameters.
  kGCMServiceErrorCodeInvalidParameters = 1002,

  // Invalid missing to.
  kGCMServiceErrorCodeMissingTo = 1003,

  // GCM could not cache the message for sending.
  kGCMServiceErrorSave = 1004,

  // Message size exceeded (size > 4KB).
  kGCMServiceErrorSizeExceeded = 1005,

  /**
   *  GCM Connect errors.
   */

  // GCM already connected with the client.
  kGCMServiceErrorCodeAlreadyConnected = 2001,

  /**
   *  PubSub errors.
   */

  // Topic already subscribed to.
  kGCMServiceErrorCodePubSubAlreadySubscribed = 3001,

  // Topic already unsubscribed from.
  kGCMServiceErrorCodePubSubAlreadyUnsubscribed = 3002,

  // Invalid topic name, does not match the topic regex "/topics/[a-zA-Z0-9-_.~%]+"
  kGCMServiceErrorCodePubSubInvalidTopic = 3003,
};

error codes end at 3003!

A: I have seen this before because I didn't start GCM before using GCMPubSub. So this should fix it for you
var config = GCMConfig.defaultConfig()
// Note you should only call start once during the lifetime of your app.
GCMService.sharedInstance().startWithConfig(config)
GCMPubSub.sharedInstance().subscribeWithToken(registrationId, topic: "/topics/mytopic", options: nil) { error in
    print(error.localizedDescription)
}

A: The problem for me was that you cannot even call
GCMPubSub.sharedInstance() until you call GCMService.sharedInstance().startWithConfig(config)
so you cannot store GCMPubSub.shareInstance() as a property before actually calling subscribeWithToken


text:
Q: Javascript Update href of  tag on page load I've written a code that looks like this. I should update every href of the  tags that have the url I want to change.

Unfortunately the href is always the same.
Here is the button in which my  tag is contained.

"Voglio diventare un Copywriter!"
Compila il questionario per accedere alla consulenza gratuita introduttiva

Here is the  tag:

"Voglio diventare un Copywriter!"
Compila il questionario per accedere alla consulenza gratuita introduttiva

A: You can do like this
    let anc = document.getElementsByTagName('a');
    for (const ancr of anc) {
        if (ancr.href.includes('myoldurl')) {
            const ahref = ancr.href.replace('myoldurl', 'mynewurl');
            ancr.href = ahref;
        }
    }

A: You don't need to .item class name in query selector because your  element hasn't this class. Try this.

btn.onclick = function changeUrl () {
  var newUrl = "https://pietroscataglini.typeform.com/to/c4dAZYjg";
  /*
  var myArr = url.split("?");
  myArr[0] = "mynewurl";
  var new_url = myArr.join("#");
  */

  $("a[href='myoldurl']").prop("href", newUrl);
  $("#message").text(newUrl);
}
#message {
 color: red
}

    "Voglio diventare un Copywriter!"
    Compila il questionario per accedere alla consulenza gratuita introduttiva

Now href value is "myoldurl".

When you click on the button it will replace with your new url.

<input type="button" id="btn" value = "Change">


text:
Q: Is there a way to create a (compressed) squashfs that contains an uncompressed file We have a large file that needs to be uncompressed inside a compressed squashfs.
Is this possible without patching mksquashfs?

Something like this would be nice:
$ mksquashfs existing_squash.sqsh
             -uncompressed my_big_file.txt
             new_squash.sqsh

A: There didn't seem like a straightforward way of doing the above, so we decided to copy that large file to an uncompressed location once when we copy the flash to the device.


text:
Q: wglCreateContextAttribsARB fails on NVIDIA Hardware ContextWin32::ContextWin32(WindowHandle parent, NLOpenGLSettings settings)
: IPlatformContext(parent, settings)
{
    int pf = 0;
    PIXELFORMATDESCRIPTOR pfd = {0};
    OSVERSIONINFO osvi = {0};
    osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);

    // Obtain HDC for this window.
    if (!(m_hdc = GetDC((HWND)parent)))
    {
        NLError("[ContextWin32] GetDC() failed.");
        throw NLException("GetDC() failed.", true);
    }

    // Create and set a pixel format for the window.
    pfd.nSize = sizeof(pfd);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = settings.BPP;
    pfd.cDepthBits = settings.BPP;
    pfd.iLayerType = PFD_MAIN_PLANE;

    // Obtain Windows Version
    if (!GetVersionEx(&osvi))
    {
        NLError("[ContextWin32] GetVersionEx() failed.");
        throw NLException("[ContextWin32] GetVersionEx() failed.");
    }

    // Get a pixelformat, based on our settings
    pf = ChoosePixelFormat(m_hdc, &pfd);

    // Set the pixelformat
    if (!SetPixelFormat(m_hdc, pf, &pfd))
    {
        NLError("[ContextWin32] GetVersionEx() failed.");
        throw NLException("[ContextWin32] SetPixelFormat() failed.");
    }

    // When running under Windows Vista or later support desktop composition.
    // This doesn't really apply when running in full screen mode.
    if (osvi.dwMajorVersion > 6 || (osvi.dwMajorVersion == 6 && osvi.dwMinorVersion >= 0))
        pfd.dwFlags |= PFD_SUPPORT_COMPOSITION;

    // Verify that this OpenGL implementation supports the extensions we need
    std::string extensions = wglGetExtensionsStringARB(m_hdc);
    if (extensions.find("WGL_ARB_create_context") == std::string::npos){
        NLError("[ContextWin32] Required extension WGL_ARB_create_context is not supported.");
        throw NLException("[ContextWin32] Required extension WGL_ARB_create_context is not supported.");
    }

    int attribList[] =
    {
        WGL_CONTEXT_MAJOR_VERSION_ARB, settings.MAJOR,
        WGL_CONTEXT_MINOR_VERSION_ARB, settings.MINOR,

        WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB,
        WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
        WGL_DRAW_TO_WINDOW_ARB, GL_TRUE,
        WGL_SUPPORT_OPENGL_ARB, GL_TRUE,
        WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
        WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB,
        WGL_COLOR_BITS_ARB, 32,
        WGL_DEPTH_BITS_ARB, 24,
        0
    };

    // First try creating an OpenGL context.
    if (!(m_hglrc = wglCreateContextAttribsARB(m_hdc, 0, attribList)))
    {
        // Fall back to an OpenGL 3.0 context.
        attribList[3] = 0;
        if (!(m_hglrc = wglCreateContextAttribsARB(m_hdc, 0, attribList))){
            NLError("[ContextWin32] wglCreateContextAttribsARB() failed for OpenGL 3 context.");
            throw NLException("[ContextWin32] wglCreateContextAttribsARB() failed for OpenGL 3 context.", true);
        }
    }

    if (!wglMakeCurrent(m_hdc, m_hglrc)){
        NLError("[ContextWin32] wglMakeCurrent() failed for OpenGL 3 context.");
        throw NLException("[ContextWin32] wglMakeCurrent() failed for OpenGL 3 context.");
    }

    // Load wglSwapIntervalExt
    typedef BOOL (APIENTRY * PFNWGLSWAPINTERVALEXTPROC)(int);
    static PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
    wglSwapIntervalEXT = reinterpret_cast<PFNWGLSWAPINTERVALEXTPROC>(wglGetProcAddress("wglSwapIntervalEXT"));

    if ( wglSwapIntervalEXT )
    {
            if ( settings.VSYNC == true )
            {
                wglSwapIntervalEXT(1);
            }
            else if ( settings.VSYNC == false )
            {
                wglSwapIntervalEXT(0);
            }
    }
    else if (wglSwapIntervalEXT == NULL )
    {
        NLWarning("[ContextWin32] Cannot load wglSwapIntervalEXT");
    }
}

This is the code in question.
It fails on Line 77, when I try to set the Attributes.
But the very same code works on my ATI.
I do not own any NVIDIA Product and cannot reproduce it, but I need to fix it of course. Can anyone help on the issue? What did I overlook?
My Definitions:
extern "C" {

#define ERROR_INVALID_VERSION_ARB               0x2095
#define WGL_CONTEXT_DEBUG_BIT_ARB               0x0001
#define WGL_CONTEXT_FLAGS_ARB                   0x2094
#define WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB  0x0002
#define WGL_CONTEXT_LAYER_PLANE_ARB             0x2093
#define WGL_CONTEXT_MAJOR_VERSION_ARB           0x2091
#define WGL_CONTEXT_MINOR_VERSION_ARB           0x2092
#define WGL_CONTEXT_CORE_PROFILE_BIT_ARB            0x00000001
#define WGL_CONTEXT_PROFILE_MASK_ARB            0x9126

#define WGL_NUMBER_PIXEL_FORMATS_ARB            0x2000
#define WGL_DRAW_TO_WINDOW_ARB                  0x2001
#define WGL_DRAW_TO_BITMAP_ARB                  0x2002
#define WGL_ACCELERATION_ARB                    0x2003
#define WGL_NEED_PALETTE_ARB                    0x2004
#define WGL_NEED_SYSTEM_PALETTE_ARB             0x2005
#define WGL_SWAP_LAYER_BUFFERS_ARB              0x2006
#define WGL_SWAP_METHOD_ARB                     0x2007
#define WGL_NUMBER_OVERLAYS_ARB                 0x2008
#define WGL_NUMBER_UNDERLAYS_ARB                0x2009
#define WGL_TRANSPARENT_ARB                     0x200A
#define WGL_TRANSPARENT_RED_VALUE_ARB           0x2037
#define WGL_TRANSPARENT_GREEN_VALUE_ARB         0x2038
#define WGL_TRANSPARENT_BLUE_VALUE_ARB          0x2039
#define WGL_TRANSPARENT_ALPHA_VALUE_ARB         0x203A
#define WGL_TRANSPARENT_INDEX_VALUE_ARB         0x203B
#define WGL_SHARE_DEPTH_ARB                     0x200C
#define WGL_SHARE_STENCIL_ARB                   0x200D
#define WGL_SHARE_ACCUM_ARB                     0x200E
#define WGL_SUPPORT_GDI_ARB                     0x200F
#define WGL_SUPPORT_OPENGL_ARB                  0x2010
#define WGL_DOUBLE_BUFFER_ARB                   0x2011
#define WGL_STEREO_ARB                          0x2012
#define WGL_PIXEL_TYPE_ARB                      0x2013
#define WGL_COLOR_BITS_ARB                      0x2014
#define WGL_RED_BITS_ARB                        0x2015
#define WGL_RED_SHIFT_ARB                       0x2016
#define WGL_GREEN_BITS_ARB                      0x2017
#define WGL_GREEN_SHIFT_ARB                     0x2018
#define WGL_BLUE_BITS_ARB                       0x2019
#define WGL_BLUE_SHIFT_ARB                      0x201A
#define WGL_ALPHA_BITS_ARB                      0x201B
#define WGL_ALPHA_SHIFT_ARB                     0x201C
#define WGL_ACCUM_BITS_ARB                      0x201D
#define WGL_ACCUM_RED_BITS_ARB                  0x201E
#define WGL_ACCUM_GREEN_BITS_ARB                0x201F
#define WGL_ACCUM_BLUE_BITS_ARB                 0x2020
#define WGL_ACCUM_ALPHA_BITS_ARB                0x2021
#define WGL_DEPTH_BITS_ARB                      0x2022
#define WGL_STENCIL_BITS_ARB                    0x2023
#define WGL_AUX_BUFFERS_ARB                     0x2024
#define WGL_NO_ACCELERATION_ARB                 0x2025
#define WGL_GENERIC_ACCELERATION_ARB            0x2026
#define WGL_FULL_ACCELERATION_ARB               0x2027

#define WGL_SWAP_EXCHANGE_ARB                   0x2028
#define WGL_SWAP_COPY_ARB                       0x2029
#define WGL_SWAP_UNDEFINED_ARB                  0x202A

#define WGL_TYPE_RGBA_ARB                       0x202B
#define WGL_TYPE_COLORINDEX_ARB                 0x202C

extern HGLRC wglCreateContextAttribsARB(HDC hDC, HGLRC hShareContext, const int *attribList);

}

Maybe I got some #defines wrong?
Any input is highly appreciated.
ps.: The little glitch regarding AttribList[3] = 0; is fixed by now, must be 1. But that was not the issue.

A: Remove from 'attribList' the following pairs:

*

*WGL_ACCELERATION_ARB

*WGL_DRAW_TO_WINDOW_ARB

*WGL_SUPPORT_OPENGL_ARB (obvious that support OpenGL!)

*WGL_DOUBLE_BUFFER_ARB

*WGL_PIXEL_TYPE_ARB

*WGL_COLOR_BITS_ARB

*WGL_DEPTH_BITS_ARB

Those attribute names are already specified by the '*m_hdc*' handle (infact you call SetPixelFormat on it).
I create a valid context without those flags on NVIDIA platforms.
Valid attribute names for CreateContextAttribsARB are:
WGL_CONTEXT_MAJOR_VERSION_ARB       0x2091
WGL_CONTEXT_MINOR_VERSION_ARB       0x2092
WGL_CONTEXT_LAYER_PLANE_ARB     0x2093
WGL_CONTEXT_FLAGS_ARB           0x2094
WGL_CONTEXT_PROFILE_MASK_ARB        0x9126

Furthermore, what error is returning wglCreateContextAttribsARB?
Instance example:
int err = Gl.GetError();

switch (err) {
    case Gl.INVALID_OPERATION:
        throw new InvalidOperationException(String.Format("unable to create context {0}.{1} ({2})", sVersionDb[version].GLMajor, sVersionDb[version].GLMinor, "invalid operation"));
    case Wgl.ERROR_INVALID_VERSION_ARB:
        throw new InvalidOperationException(String.Format("unable to create context {0}.{1} ({2})", sVersionDb[version].GLMajor, sVersionDb[version].GLMinor, "invalid version"));
    case Wgl.ERROR_INVALID_PROFILE_ARB:
        throw new InvalidOperationException(String.Format("unable to create context {0}.{1} ({2})", sVersionDb[version].GLMajor, sVersionDb[version].GLMinor, "invalid profile"));
    case Wgl.ERROR_INVALID_PIXEL_TYPE_ARB:
        throw new InvalidOperationException(String.Format("unable to create context {0}.{1} ({2})", sVersionDb[version].GLMajor, sVersionDb[version].GLMinor, "invalid pixel format"));
    default:
        throw new InvalidOperationException(String.Format("unable to create context {0}.{1} ({2})", sVersionDb[version].GLMajor, sVersionDb[version].GLMinor, "unknown error " + err));
}


text:
Q: Multiple instances of flowplayer (flash video) does not play sound in IE7 I got page which has multiple instances of flowplayer (all but one hidden at any one time).
It works fine on all browsers except (obviously) IE7, for which first 32 instances of the flash player work fine, however starting with 33rd instance of the video player I am not getting any sound (just visuals).
I am completely lost at this one - does IE have a limit of how many sound channels it can support? Or destroy and recreate video flash objects with javascript?
Any ideas?


text:
Q: Beginner questions about Qt I want to ask some questions which I couldn't find in Qt's website.

*

*Is Qt completely free or just some part of it, or not free at all?

*Can I use its library in Visual Studio?

*Can I use MFC with Qt together?

*The main reason I want to use Qt is to create professional GUI's. What should I actually download? Qt Library, Qt Creator or both?

A: *

*It is available free under the LGPL license. Click here to read the circumstances under which it can be used for free. Briefly - you can use it to produce proprietary / commercial software as long as you allow the user to modify / update the Qt dependencies. Typically this means dynamic linking but you can also statically link if you provide your users with the means to rebuild. You can also statically link if you are only going to use the software internally within your company (i.e. not distribute it).

*Yes, and they have a Visual Studio plugin to make it easier.

*Yes. Although it's hard to see why you would want to unless you're dealing with legacy code. MFC is outdated, awkward to use, and platform specific vs. Qt which is modern, easy to use, and cross platform.

*It depends how you want to go about doing it. Just the library is fine if you are going to use it in your own IDE. Alternatively, you can use their IDE, which is Qt Creator, but that is optional. It's worth at least having Qt Designer, which is a tool for building GUIs visually. That is also optional, as you can hand code your GUIs if you wish.

A: *

*Qt is free (as in free speech and as in free beer): "Qt is available under GPL v3, LGPL v2 and a commercial license".

*yes, there's even a plugin (that works for professional visual studio versions).

*Why? well anyway, through both libraries you can get native windows handles, so, it's one way of tampering with both at the same time, maybe. But, nor Qt or MFC is made to support one another.

*Qt Library is what your source will be based on, Qt Creator is an IDE on its own, whether you'll use it or not for developing for Qt is an option. I myself use Vim and recent versions of cmake instead of qmake when I can.


text:
Q: Generate a list of files from a file containing a series of globbing patterns I am looking for a way to build a list of files by parsing a file that contains a sequence of zsh globbing patterns.
The final goal is to pass this list of files to  hg add in mercurial. For those interested in this specific part, my question is motived by this other question that I asked in StackOverflow:

*

*Mercurial "hginclude"? (globbing syntax to specify which files to track)
A sample file (let's call it .hginclude) would look as follows:
.zshrc
.zprofile
.less*
.emacs*/**
src*/**
.hg*
.bash*
.inputrc
.ssh

and the output from the script should be a list of files obtained by collecting the output of
print globbing_pattern
on every line, where globbing_pattern refers to each line in the file .hginclude above.
Ultimately, the list of files should be a list that I can pass to hg add to track those files in mercurial.
The assumption for this part is that I have an .hgignore with the following:
syntax: glob
*

which means: don't track anything unless explicitly added via an hg add command.

A: See hg help patterns. Mercurial supports reading file names from a file, so you can do
$ hg add listfile:myfiles.txt

and have myfiles.txt contain the file names to add. What's even more interesting for you is that a "file name" in Mercurial can be a glob pattern. So you can have myfiles.txt contain
.zshrc
.zprofile
glob:.less*
glob:.emacs*/**

etc, and the hg add command above will do the right thing.
You can even use file sets to select the files. This is a find-like language that lets you do things like
set:exec() and not binary()

to select executable files that are not binary, i.e., scripts.

The above commands will respect the .hgignore file and so you cannot use them directly to solve your problem. However, you can use
$ hg status --all --no-status listfile:myfiles.txt

to get a list of files matches by the patterns, including any files that would normally be ignored. You can then proceed to use this file list with hg add:
$ hg status -A -n -0 listfile:myfiles.txt | xargs -0 hg add

A: Try this:
 hg add `for i in `cat myfiles.txt` ; do ls $i ; done`

where myfiles.txt contains the globs.
But of course the suggestion of initrpc is cleaner.


text:
Q: Specific composition of probability kernels yields a probability kernel Question: Let $(X, \mathcal{X})$, $(Y,\mathcal{Y})$ and $(Z,\mathcal{Z})$ be measurable spaces. Let $\kappa_1:X \times \mathcal{Y} \to [0,1]$ and $\kappa_2:X \times Y \times \mathcal{Z} \to [0,1]$ be probability kernels.
Then, is the following $\kappa:X \times \mathcal{Z} \to [0,1]$ a probability kernel?
$$
\kappa(x,S) := \int_{y \in Y} \kappa_2(x,y,S) \kappa_1(x)(dy)
$$
Definitions: The integral is the Lebesgue integral with respect to measure $\kappa_1(x)$. $\kappa_2: (X \times Y) \times \mathcal{Z} \to [0,1]$ is a probability kernel in the sense that the $\sigma$-algebra on $X \times Y$ is generated in the usual way (by $\mathcal{X} \times \mathcal{Y}$).

A: The following Lemma comes from How to construct Markov kernels into a product measurable space? :

Let $\kappa_1:X \times \mathcal{Y} \to [0,1]$ and $\kappa_1':X \times \mathcal{Z} \to [0,1]$ be probability kernels for measurable spaces $(X, \mathcal{X})$, $(Y, \mathcal{Y})$ and $(Z, \mathcal{Z})$. Then, $\kappa_1 \times \kappa_1':X \times \mathcal{P} \to [0,1]$ is a probability kernel, where
  $$
\kappa_1 \times \kappa_1'(x) = \kappa_1(x) \times \kappa_1'(x)
$$
  $\mathcal{P}$ is the $\sigma$-algebra on $Y \times Z$ generated by $\mathcal{Y} \times \mathcal{Z}$. $\kappa_1(x) \times \kappa_1'(x)$ is the product of the two measures $\kappa_1(x)$ and $\kappa_1'(x)$. This product exists and is unique (because $\kappa_1(x)$ and $\kappa_1'(x)$ are probability measures).

Then, let $\kappa_1'' := \kappa_1 \times \delta$, where $\delta:X \times \mathcal{X} \to [0,1]$ with $\delta(x)(S) = [x \in S]$ is the dirac delta.
\begin{align*}
\kappa(x,S) &= \int_{y \in Y} \kappa_2(x,y,S) \kappa_1(x)(dy) \\
&= \int_{x' \in X} \delta(x)(dx') \int_{y \in Y} \kappa_2(x',y,S) \kappa_1(x)(dy) && \text{property of dirac delta} \\
&= \int_{(x',y) \in X \times Y} \kappa_2(x',y,S) (\delta(x) \times \kappa_1(x))(d(x',y)) && \text{Fubini} \\
&= \int_{(x',y) \in X \times Y} \kappa_2(x',y,S) (\delta \times \kappa_1)(x)(d(x',y)) \\
&= \int_{(x',y) \in X \times Y} \kappa_2(x',y,S) \kappa_1''(x)(d(x',y)) \\
&= (\kappa_1'' >=> \kappa_2)(x)(S)
\end{align*}
The last line describes a probability kernel because it describes Kleisli composition of the probability kernels $\delta \times \kappa_1$ and $\kappa_2$.


text:
Q: How to save video from assets url I want to save video to my app document from asset url. My asset url is as follows:-
"assets-library://asset/asset.MOV?id=1000000394&ext=MOV"

I tried this:-
NSString *str=@"assets-library://asset/asset.MOV?id=1000000394&ext=MOV";
NSData *videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:str]];
[videoData writeToFile:mypath atomically:YES];

but on the second line [NSData dataWithContentsOfURL:[NSURL URLWithString:str]] i got program crash with this reason:-
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSURL length]: unrecognized selector sent to instance
I want to know how to access asset video url.
Thanx for any help.

A: thanks for this.. all i needed to change was
    errorBlock:^(NSError *err)

to this:
    failureBlock :^(NSError *err)

A: I think your best bet is to use the method
getBytes:fromOffset:length:error:

of
ALAssetRepresentation

You can get the default representation of an asset like so
ALAssetRepresentation *representation = [someVideoAsset defaultRepresentation];

So off the top of my head it should go something like this (I'm away from my Mac so this hasn't been tested)
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:videoUrl resultBlock:^(ALAsset *asset) {
    ALAssetRepresentation *rep = [asset defaultRepresentation];
    Byte *buffer = (Byte*)malloc(rep.size);
    NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:rep.size error:nil];
    NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
    [data writeToFile:filePath atomically:YES];
} errorBlock:^(NSError *err) {
    NSLog(@"Error: %@",[err localizedDescription]);
}];

Where videoUrl is the asset url of the video you're trying to copy, and filePath is the path where you're trying to save it to.


text:
Q: How to remove pdfannotextractor copyright text from the generated pdf Hi I generated a pdf with the help of pdflatex and pdfannotextractor.
First of all, thanks for pdfannotextractor this helped me to generate a pdf without missing any links in the inlcuded pdf.
After generating the pdf, I saw a additional page which contains the pdfannotextractor copyright text. How to remove this page.

I need to remove this page.
My pdfannotextractor version is PDFAnnotExtractor 2012/04/18 v0.1l


text:
Q: return type of void* in c++ Can I declare a return type of void * for a c++ function? I am working in the Linux environment and I want to return a void * for library handle in case of dlopen for shared library.

A:
Can I declare a return type of void * for a c++ function?

Yes, you can. It's one way to return an opaque pointer.
Another would be:
struct Foo;
Foo* bar();


text:
Q: Symfony2 (FOSUserBundle Registration form) One to one relation between User class and another class I've found a similar question but the reported solution didn't work for me.
Here is the link: FOSUserBundle One-To-One mapped Entity not saved
Probably I'm missing something.
Current situation:
I'm using the FOSUserBundle to register new users. The users' data are split between two tables with corresponding Entities and ONE TO ONE relation (one table contains the authentication credentials and the other one the users' profile data like name/surname etc). I've overwritten the basic RegistrationFormType as shown in the FOSUserBundle's documentation. Now the data are persisted successfully TO BOTH TABLES..... BUT the foreign key field remains empty (in my case "utente_id" field, or $utente variable in DatiUtente entity)
Here are the gist files for you:

*

*Utente (Entity - main User class)  https://gist.github.com/gittix09/8fcac25594cb435b7932

*DatiUtente (Entity)  https://gist.github.com/gittix09/321b5d22f0330f63fb02

*RegistrationFormType  https://gist.github.com/gittix09/0bb3964d92c12a8fb139

*DatiUtenteFormType  https://gist.github.com/gittix09/889533d9f21890a03724

*RegistrationController  https://gist.github.com/gittix09/12d953621cfc8b503ff8

*RegistrationFormHandler  https://gist.github.com/gittix09/9de1ac967de8ff23995f
In the gist files I changed the project name with "XX" but of course in my code it's correct.
Also, in config.yml
# Fos UserBundle Configuration:
fos_user:
 registration:
        form:
            type: ac_user_registration

#Services list
services:
ac_user.registration.form.type:
      class: XX\UserBundle\Form\Type\RegistrationFormType
      arguments: [%fos_user.model.user.class%]
      tags:
          - { name: form.type, alias: ac_user_registration }

A: In DatiUtente Entity change setUtente() like this :
  public function setUtente(\XX\UserBundle\Entity\Utente $utente = null)
    {
        $utente->setDatiutente($this);
        $this->utente = $utente;
        return $this;
    }

A: Solution:
In the end I changed the direction of the relationship between the two entities (Utente and DatiUtente).


text:
Q: How to plot percentages instead of counts in ggplot2 geom_col (R)? I have a dataset with the number of impressions from a unique user and whether this user has been converted = 1, or not (=0). I want to create a col chart that displays the conversion rate for intervals of 20 impressions. Meaning that for each interval, the conversion rate is the number of converted users in that interval of impressions, divided by the number of unique users in that interval.
So for instance, for this dataset:
# A tibble: 19 x 2
   converted tot_impr
       <dbl>    <dbl>
 1         0       19
 2         0        4
 3         1       19
 4         0       13
 5         0       18
 6         1        9
 7         1       17
 8         1        8
 9         1        8
10         1       11
11         0        8
12         0       19
13         1        8
14         0        8
15         1       18
16         0       12
17         1        5
18         1       12
19         0        1

I should be seeing those conversion rates:

I have managed to count the number of converted users per interval using ggplot2 geom_col using the following code:
ggplot(data = db) +
  geom_col(mapping = aes(x = tot_impr, y = converted), width=5)

I am struggling to force geom_col to display not the converted count in the y-axis, but to display the percentage of converted in relation to the total number of individual samples in that interval of impressions.
Could someone help me out?
Thank you in advance!

A: Try with this. It is better to compute your variables before plotting:
library(dplyr)
library(ggplot2)
#Code
df %>% mutate(Cut=cut(tot_impr,breaks = seq(0,20,by=5),include.lowest = T,
                      right = T,dig.lab = 10)) %>%
  group_by(Cut) %>%
  summarise(N=n(),converted=sum(converted)) %>%
  mutate(conv_rate=converted/N) %>%
  ggplot(aes(x=Cut,y=conv_rate))+
  geom_bar(stat='identity',fill='magenta')+
  scale_y_continuous(labels = scales::percent)

Output:

Some data used:
#Data
df <- structure(list(converted = c(0L, 0L, 1L, 0L, 0L, 1L, 1L, 1L,
1L, 1L, 0L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L), tot_impr = c(19L,
4L, 19L, 13L, 18L, 9L, 17L, 8L, 8L, 11L, 8L, 19L, 8L, 8L, 18L,
12L, 5L, 12L, 1L)), row.names = c(NA, -19L), class = "data.frame")


text:
Q: nginx rewrite in proxy_pass I need proxing to different backend but whith same url, so rewriting thould be
like this
URL: http://myservrer.com/server/monitoring1?(parameters)
REWRITE TO: http://1.1.1.1/server/monitoring?(parameters)

URL: http://myservrer.com/server/monitoring2?(parameters)
REWRITE TO: http://2.2.2.2/server/monitoring?(parameters)

My current config:
location /server/monitoring1 {
proxy_pass http://1.1.1.1:82/server/monitoring;
}
location /server/monitoring2 {
proxy_pass http://2.2.2.2:82/server/monitoring;
}

How to change it with rewrite options?

A: location /server/monitoring1 {
    rewrite ^/server/monitoring1\?(.*) http://1.1.1.1:82/server/monitoring?$1 redirect;
}
location /server/monitoring2 {
    rewrite ^/server/monitoring2\?(.*) http://2.2.2.2:82/server/monitoring?$1 redirect;
}


text:
Q: CSS rotate animation translates the element I'm having trouble (again) understanding CSS animations- specifically this rotate animation. When you hover over the image it should start to rotate back-and-forth. It does this, but only after shifting over to the bottom left. I've been looking for similar questions but haven't found an answer as to why this happens or how to prevent it.

img {

  position: absolute;

  top: 50%;

  left: 50%;

  transform: translate(-50%, -50%);

}

img:hover {

  animation-name: freakout;

  animation-duration: .5s;

  animation-iteration-count: infinite;

}

@keyframes freakout {

  0%, 100% {

    -ms-transform: rotate(0deg);

    /* IE 9 */

    -webkit-transform: rotate(0deg);

    /* Chrome, Safari, Opera */

    transform: rotate(0deg);

  }

  50% {

    -ms-transform: rotate(7deg);

    /* IE 9 */

    -webkit-transform: rotate(7deg);

    /* Chrome, Safari, Opera */

    transform: rotate(7deg);

  }

}

A: Reason behind this is that in img tag Transform property uses Translate function so as to align the image to center but the moment you hover over the image the Transform property changes to Rotate property resulting in shifting of position while hovering over the image.I changed the code ,This will work.

   img {

  position: absolute;

  top: 50%;

  left: 50%;

  transform: translate(-50%, -50%);

}

img:hover {

  animation-name: freakout;

  animation-duration: .5s;

  animation-iteration-count: infinite;

}

@keyframes freakout {

  0%, 100% {

    -ms-transform: rotate(0deg)translate(-50%, -50%);

    /* IE 9 */

    -webkit-transform: rotate(0deg)translate(-50%, -50%);

    /* Chrome, Safari, Opera */

    transform: rotate(0deg)translate(-50%, -50%);

  }

  50% {

    -ms-transform: rotate(7deg)translate(-50%, -50%);

    /* IE 9 */

    -webkit-transform: rotate(7deg)translate(-50%, -50%);

    /* Chrome, Safari, Opera */

    transform: rotate(7deg)translate(-50%, -50%);

  }

}


text:
Q: determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array def almostIncreasingSequence(sequence):
    if sorted(sequence)==sequence:
        return True
    else:
        seq1=sequence[:]
        flag=0
        for i in range(len(seq1)):
            sequence.pop(i)
            num=check_sorted(sequence)
            if num==1:
                flag=1
                break
            else:
                sequence=seq1[:]
        if flag==1:
            return True
        else:
            return False

def check_sorted(sequence):
    check=0
    for i in range(len(sequence)-1):
        if sequence[i]<sequence[i+1]:
            check=1
        else:
            check=0
    #if sorted(sequence)==sequence:
        #return 1
    #else:
        #return 0
    return check

Can u please tell wt wrong I m dng here?
Input:
sequence: [1, 2, 1, 2]
Output:
true
Expected Output:
false

A: def strictly_increasing_sequence(sequence):
    N = len(sequence)
    for i in range(N - 1):
        if (sequence[i] >= sequence[i+1]):
            return False
    return True

def check_sequence(sequence):
    if strictly_increasing_sequence(sequence):
        print("The sequence was strictly increasing from the beginning")
        return True
    else :
        N = len(sequence)
        for i in range(N):
            subsequence = sequence[:i]+ (sequence[i+1:] if i < N - 1 else [])
            if strictly_increasing_sequence(subsequence):
                print("By pop item {} it works".format(i))
                return True
    return False


text:
Q: What is time consuming using Dotfuscator? I have to obfuscate a large solution (~200 assemblies) using Dotfuscator Pro 4.10. The last run took ~4hr, and this is quite long, much longer than the build itself. What is so time consuming? I mean, I can modify my settings. Maybe I ask it to perform a job that takes a very long time but is not essential to me.
Any idea?
Thanks.
Update: my code is in C++/CLI with native calls.

A: There are some things you can try:

*

*Don't run the build in the Dotfuscator GUI.  Instead, run at the command line or with MSBuild.

*On the Settings tab > Global Options, under General, set the Build Progress to "Quiet".

*On the Settings tab > Reports > Smart Obfuscation, set the Report Verbosity to "Warnings Only".


text:
Q: JavaScript - Is it necessary to check for condtion first I was wondering if it is necessary to check for the condition in this particular example.
The condition I'm talking about is if ( Id.indexOf("_") ).
It just checks to see if Id has an underscore and if so then set the variable to strip the underscore and replace with hyphen.
I know I can just use Id = Id.split("_").join("-"); without the if statement checking to see if the condition is true, but just wondering if in this case is it good practice to check for the condition first or not?
Which way would you do it? And explain why please.
    Id = "My_ID";
    var brand = "The Brand";
    var b = brand.trim().toLowerCase();
    var page = b.split(/\W+/g).join("-");

    if ( Id.indexOf("_") ) {
      Id = Id.split("_").join("-");
    }

A: If there is no underscore your split() won't do anything, so no - there's no need for the if here. Go with something like that and you're fine:
Id = Id.split("_").join("-");

or
Id = Id.replace(/_/g, '-');

to avoid creating an array first.

A: This could answer your question:
console.log("mytext".split("_").join("-"));  // mytext
console.log("my_text".split("_").join("-")); // my-text

furthermore condition in your code if (Id.indexOf("_")) does not work as you intended. You need to use if (Id.indexOf("_") > -1) or (~Id.indexOf("_"))


text:
Q: How can I get the average color of an image? I want to be able to take an image and find out what is its average color, meaning if the image is half black and half white, I would get something in-between... some shade of gray. It could be the most frequent single color  or median. Any average will do.
How can I do this in Android?

A: Bitmap bitmap = someFunctionReturningABitmap();
long redBucket = 0;
long greenBucket = 0;
long blueBucket = 0;
long pixelCount = 0;

for (int y = 0; y < bitmap.getHeight(); y++)
{
    for (int x = 0; x < bitmap.getWidth(); x++)
    {
        Color c = bitmap.getPixel(x, y);

        pixelCount++;
        redBucket += Color.red(c);
        greenBucket += Color.green(c);
        blueBucket += Color.blue(c);
        // does alpha matter?
    }
}

Color averageColor = Color.rgb(redBucket / pixelCount,
                                greenBucket / pixelCount,
                                blueBucket / pixelCount);

A: Use the Bitmap.getPixels() method to get the color values. Then to calculate the average you have to decide what you mean by that. In a grayscale image it is simple, but with colors there are no such thing as an average. You can separate into components (for example RGBA), and take the average of each component. An alternative is to search for the most commonly used color, and there are several other options I'm sure. Play with it :)

A: There is also a library that can do this for you.
http://www.michaelevans.org/blog/2013/12/12/colorart-a-library-to-do-itunes-11-style-color-matching-for-android/

A: Expanding on the second idea from Stephane Mathis' answer, you can resize the image to 1x1 and get the color of that image:
Bitmap originalBitmap = /*your original image*/;
Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, 1, 1, false);    //Resize the bitmap to 1x1
@ColorInt int averageColor = scaledBitmap.getPixel(0, 0);    //Get the color of the only pixel of the 1x1 bitmap

If your original image is not a Bitmap object, you can convert it to a Bitmap using one of the methods described here.

A: I think you will have to do that yourself.
Just create an int array with all the colors:
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
bmp = bmp.copy(Bitmap.Config.ARGB_8888, true);
int intArray[] = new int[bmp.getWidth()*bmp.getHeight()];
bmp.getPixels(intArray, 0, bmp.getWidth(), 0, 0, bmp.getWidth(), bmp.getHeight());

Then you can get the color with intArray[0], the value could be 0xFFFF0000 for red (last 6 numbers are the RGB color value).
Here is another easy solution:

*

*Get you full-size image in a bitmap.

*Create a scaled bitmap of 1*1px.

*Get this bitmap color.

A: Building off Dan O's solution, here's a method that automatically takes into account the alpha channel and makes the optimization/ tradeoff of getPixels vs getPixel.
The cost is memory but the benefit is performance, invocation of a virtual method in a loop that could possibly be run several million times [i.e. an 8MP image has 3,456x2,304 = 7,962,624 pixels]). I've even taken things one step further by removing the looped android.graphics.Color method calls.
public static int getDominantColor(Bitmap bitmap) {
   if (null == bitmap) return Color.TRANSPARENT;

   int redBucket = 0;
   int greenBucket = 0;
   int blueBucket = 0;
   int alphaBucket = 0;

   boolean hasAlpha = bitmap.hasAlpha();
   int pixelCount = bitmap.getWidth() * bitmap.getHeight();
   int[] pixels = new int[pixelCount];
   bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());

   for (int y = 0, h = bitmap.getHeight(); y < h; y++)
   {
       for (int x = 0, w = bitmap.getWidth(); x < w; x++)
       {
           int color = pixels[x + y * w]; // x + y * width
           redBucket += (color >> 16) & 0xFF; // Color.red
           greenBucket += (color >> 8) & 0xFF; // Color.greed
           blueBucket += (color & 0xFF); // Color.blue
           if (hasAlpha) alphaBucket += (color >>> 24); // Color.alpha
       }
   }

   return Color.argb(
           (hasAlpha) ? (alphaBucket / pixelCount) : 255,
           redBucket / pixelCount,
           greenBucket / pixelCount,
           blueBucket / pixelCount);
}

A: You can use Palete class from AndroidX, or from the the v7-support library.
It provides additional methods to extract colours from a Bitmap, such as getting:

*

*Most Dominant color

*Vibrant colors

*Muted color

*much more

A: Here is a way to get the dominant (NOT average) colors of an image using Material color utilities library which is currently available for Java/Kotlin, C++, Dart, TypeScript.
The colors may not necessarily be the most recurring colors; the library extracts dominant colors appropriate for Material 3 design system and appropriate to be used on light or dark themes in apps.
The library is primarily used on apps for Android 12 and above and also on the Material Design website itself but I tested it for myself and got good results.
To use the library, copy-paste the code on the Material color utilities repository for your desired language to your project and then you can extract dominant colors and color schemes.
Here is an example for Java and Kotlin:
Java:
var MAX_DESIRED_COLOR_COUNT = 128;
var file = new File("my-image.jpg");
var image = ImageIO.read(file);
var pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
var colorFrequency = QuantizerCelebi.quantize(pixels, MAX_DESIRED_COLOR_COUNT);
var decentColors = Score.score(colorFrequency);
var desiredColor = decentColors.get(0);
// You can take the desiredColor or any other decentColors and forget the rest of code below

// Could also use Scheme.dark(desiredColor); to get colors suitable for dark themes
var colorScheme = Scheme.light(desiredColor);
System.out.println("Decent colors: " + decentColors);
System.out.println("Primary color (light theme): " + colorScheme.getPrimary());

Kotlin:
val MAX_DESIRED_COLOR_COUNT = 128
val file = File("my-image.jpg")
val image = ImageIO.read(file)
val pixels = image.getRGB(0, 0, image.width, image.height, null, 0, image.width)
val colorFrequency = QuantizerCelebi.quantize(pixels, MAX_DESIRED_COLOR_COUNT)
val decentColors = Score.score(colorFrequency)
val desiredColor = decentColors.first()
// You can take the desiredColor or any other decentColors and forget the rest of code below

// Could also use Scheme.dark(desiredColor) to get colors suitable for dark themes
val colorScheme = Scheme.light(desiredColor)
println("Decent colors: ${decentColors.joinToString { it.toHexString() }}")
println("Primary color (light theme): ${colorScheme.primary.toHexString()}")

fun Int.toHexString() = "#%06X".format(this and 0xFFFFFF)

Learn more about Material Design color system and color roles here (like colorScheme.primary used in the above code snippets).


text:
Q: Drop partition and rebuild global indexes "online" I am using Oracle 11g.
I have a requirement to drop a partition and rebuild global indexes. The query below does job well but BLOCKS all DML operations on the table until the indexes are rebuilt.
ALTER TABLE ABC DROP PARTITION PART1 UPDATE GLOBAL INDEXES;

But If I break the query into 2 parts and rebuilt indexes with ONLINE option separately, DML queries DOES NOT get blocked while indexes are being rebuilt
ALTER TABLE ABC DROP PARTITION PART1;
ALTER INDEX XYZ REBUILD ONLINE;

The down side of this approach is the time between the execution of drop partition and rebuilding index, those indexes will be unusable that might create performance problems.
So my question is, is there any option where I can drop partition and rebuild index "online" in one query? Currently I dont think we have following option.
ALTER TABLE ABC DROP PARTITION PART1 UPDATE GLOBAL INDEXES ONLINE;

A: Not in 11g.
Not even in 12c, but 12c makes life a bit easier, you can delay the "rebuild" part until a more appropriate time.
In 12c there is a new feature, called Asynchronous Global Index Maintenance. You can drop the partition, and that still leaves the global index usable, and marks the no longer needed index entries orphaned. Then later, you can clean up this index (DBMS_PART.CLEANUP_GIDX, or ALTER INDEX COALESCE CLEANUP, or the database can do it automatically for you as well (there is a pre-defined job for it called PMO_DEFERRED_GIDX_MAINT_JOB).

A: no global,online string,it's working with online rebuild index :
ALTER TABLE ABC DROP PARTITION PART1 UPDATE INDEXES;


text:
Q: one to one relationship between domains I'm new to Grails , i want to do one to one relationship between 2 domains for instance Author and book , so the Author has only one book  and for sure the book has one Author , i used static belongsTo in the book domain , but in the CRUD views specially in the CREATE view for the Author, it shows me a list with all the created books, i don't want that , i want to show me "Add book" if there is no books found or gets me the associated book for that author  .
thanks


text:
Q: Как отключить дискретную видеокарту Nvidia? Как отключить видеокарту Nvidia? В BIOS нет такой настройки.
Ноутбук шумит и греется, драйвера не встают нормально.

A: BIOS
Так как вопрос именно по отключению дискретной видеокарты и было упомянуто что в BIOS якобы такой настройки нет, на него и отвечаю. В твоём BIOS, а насколько помню, в каком-то из комментариев под вопросами ты писал, что он у тебя AMI BIOS (сокращаю, до абревиатуры), необходимо сделать следующие шаги.
Зайдя в BIOS у тебя будет сине-серая меню, в верхней панели навигации должны находиться следующие пункты:

Main | Advanced | Power | Boot | Tools | Exit

Сама меню вверху, в AMI разных годов может быть разная.
Далее зайди в:

Advanced -> Chipset -> SouthBridge Configuration

Далее, нажимаешь на Primary Graphics Adapter, должно всплыть окошко с вариантами выбора карты. IGP - соответственно отвечает за интегрированную видеокарту, а PCIE за Nvidia в твоём случае. Выбираешь нужную для активации. Там с которой начинается, она будет соответственно в приоритете, после выбора.
Далее необходимо выйди до уровня общего меню и соответственно выбрать пункт

Exit -> Exit & Save Changes

Ну, а дальше просто перезагрузка ноутбука с новой конфигурацией. Вроде бы ничего сложного.

Необходимые системные данные для устранения проблемы:
Что касается самой OS Debian 9, то вывести данные по поводу самого BIOS в терминале, можно воспользовавшись командой (показываю всё от root):
# dmidecode --type 0

Данные по поводу материнской платы:
# dmidecode --type baseboard

Чтобы собрать ещё больше информации, можно воспользоваться lspci - это стандартный инструмент для запроса устройств, подключенных к любой PCI-совместимой шине:
# lspci -nn

Таже можно сократить вывод до:
# lspci -k | grep -A 2 -i "VGA"

Если не установлен nvidia-detect, можно его установить и собрать данные (хотя, данных с lspci должно хватить), введя в терминале:
# nvidia-detect

Используя вышеуказанные команды, можно собрать всю необходимую информацию, для дальнейшей работы над устранением проблемы.

Nvidia
Если возникла необходимость полного удаления драйверов от Nvidia, это довольно просто сделать. Выполни следующую команду, чтобы удалить все пакеты, которые начинаются с nvidia в имени пакета:
# apt purge nvidia-*