text:
Q: Integrate ngrx into my code I'm trying to get how to add ngrx into my current project structure.
I've got all concepts around ngrx/reflux. Nevertheless, I don't quite figure out how to rebuild project structure in order to integrate it into my project.

*

*Where do I need to add reducers?

*Where do I need to add states?

*What about actions?

*Where should Store be, on a service, injected in each component?

*Where or when the data should be fetched from server?

Is there any project structure best practice over there?

A: First, you should take a look into @ngrx/store documentation : https://github.com/ngrx/store#setup
I've made a small (funny) project to demonstrate how to use :
- angular
- ngrx/store
- ngrx/effects
- normalized state
- selectors
You can find it here : https://github.com/maxime1992/pizza-sync

To give you some info about how it works :
 - core.module.ts is were I declare my root reducer
 - root.reducer.ts is were I build the root reducer and compose it with middlewares according to dev/prod env
- For a reducer, I keep every related part together (interface(s) + reducer + effects + selectors)

Then within a component, to access the store simply do like that :
Inject the store :
constructor(private _store$: Store<IStore>) { }

Get data from either
a) A selector (ex)
this._pizzasCategories$ = this._store$.let(getCategoriesAndPizzas());

b) Directly from the store (ex)
this._idCurrentUser$ = this
      ._store$
      .select(state => state.users.idCurrentUser);

Notice that I didn't subscribe which means I'm using in my view the async pipe so angular subscribe to the Observable for me.
But of course you can also do it by hand and use subscribe in your ts.

PS: I'll be releasing a starter with all that already setup to avoid loosing time with all of that when starting a new project. I'll try to release it this week and I'll update this post as soon as it's done. Maybe it might help you.
EDIT 12/05/17
Late but I finally released the starter :) !
https://github.com/maxime1992/angular-ngrx-starter


text:
Q: Existence of minimum on unbounded set and function I'm having trouble deciding if my proof of this proposition is sufficient. The proposition is,

Suppose $E \subset \mathbb{R}^N $ is open and $f:\bar{E} \to \mathbb{R}$ is continuous in $\bar{E}$. If $\bar{E}$ is unbounded, assume further that $f(x) \to +\infty$ as $\left\| x \right\| \to + \infty$, $x \in \bar{E}$. Show that $f$ attains a minimum at $z \in \bar{E}$.

I start by showing that the function must be bounded below.
Let $\inf \{ f(x) : x \in \bar{E} \} = m$ and suppose $m = - \infty$. Since $f(x) \to +\infty$ as $\left\| x \right\| \to + \infty$, there must be some compact subset $C \subset \bar{E}$ where $f(C)$ is not bounded below, but since $f$ is continuous and $C$ is compact, this is a contradiction since the continuous image of a compact set must be compact.
Now that I know $m \neq -\infty$, since $m$ is a lower bound for $f$, there exists a sequence $f(x_n) \to m$. I know $x_n$ must be bounded, since otherwise $f(x_n) \to + \infty$, so there is some compact set $X \in \bar{E}$ where $x_n \in X$. Since $f(X)$ must also be compact and therefore also closed, $f(x_n) \to m$ implies there exists $y \in X$ such that $f(x_n) \to m = f(y)$.

A: Seems good. The basic idea is that you can assume your function $f$ to be larger than some $M$ outside a large ball of radius $R$. Therefore since balls are compact the set $B_R\cap \overline E$ is compact and so your function has a minimum.

redpajama_set_name: RedPajamaStackExchange


text:
Q: OData Delete with Filter I have the problem that our backend uses an OData-"like"-Processor which has some special functions. It is oriented at OData_2.0
So the question will be:
What is the most OData like approach for this kind of the following requests
Our backend Data-Model has no single-attribute-keys. But it's recommended to be OData-Like if possible.
First: I need to delete several objects via one OData Request. My first idea is to use filters to define which objects should be deleted. But I', not sure if this is the right approach.
For Example: I want to delete all Items which have a price greater than 10.00
http://.../<oDataServiceX>/Item?$filter=ItemPrice gt 10.00

Second: When I want to delete an object which is not identifiable by one single key-attribute. How can I define that in the classical OData-Delete-Request-Syntax.
Is the following OData-like?
http://.../<oDataServiceX>/Item(1,54,2)  //3 Attributes which define the key for the Item

Or should I do a filter again? (If filter is a proper way of doing this).
http://.../<oDataServiceX>/Item?$filter=keyAttr1 eq 1 and keyAttr2 eq 54 and keyAttr 3 eq 2

A: You can't delete multiple entries in a single OData query, you need first to retrieve their keys and then send multiple delete requests. There are two ways to improve this process:

*

*Use OData batch to send all delete request in a single HTTP call.

*Use some of libraries that can simulate deletion using filter (internally they will issue multiple requests but for the application it will look like a single call). One of such libraries is Simple.OData.Client.

Hope this helps.

A: Odata v4 supports the format DELETE /entity(key1='', key2='') and so on.
However, for oData v2, one option could be to use the request body to pass some data over. DELETE /entity, with data in the body.
The documentation states that the convention is to delete an entity by key. However, this was the approach followed when we had to delete by multiple keys for an odata v2 service. Also while implementing this using oData v2 libraries, we had to add a routing convention to support Delete without a key.


text:
Q: How can I remove the screen refresh rate overlay? I somehow caused a strange issue with one of my monitors.  This happened with the previous kernel that I updated to yesterday (4/4/2021).  The issue is that there is an overlay of yellow numbers that shows the refresh rate of one of my monitors.  It showed up when I was messing with cvt / xrandr trying to get the proper monitor resolution to work (the installed kernel broke 1080p through USB-C / DP / HDMI).
The monitor resolution issue has gone away with the new kernel release (on 4/5/2021), but the refresh rate overlay is still present.  I'd post a screenshot, but the overlay doesn't capture in the screenshot.
Does anyone have any idea where this overly came from and how can I remove it?


text:
Q: Swift 3 How to save and load data I'm a software development student and for a school project me and a friend are making a iOS Swift game and we are learning Swift 3 as we progress in the game aspects.
Now, we have come to the part of the development where we question how is game data going to be saved (I'm talking about scores, player's name, in-game money, if the player plays in mute or unmute.. you know that kind of stuff)
The game uses an avatar and the player can customize it, so data customization needs to be saved too.
Right now we manage this data throught variables like
var eyeColor = "#04ff45"
var eyetype = 3 // And so on

I have done some research on this and found that there are various methods we could use.
Like, we could use Core Data or a Dictionary or a JSON file.
I'd like to know which could be the best/easiest way to acomplish this, if we need to use any specific libraries and some basic code on how to write/read the data
Thank you very much

A: Best way to save scores is by using NSUserDefaults
To save settings such as volume, you can follow the model I have below.
//When you tap on the mute button, execute this code.

   if soundSwitch { //true

       UserDefaults.standard.set(false, forKey: "SoundSwitch")
       soundSwitch = false

    } else { //false

       UserDefaults.standard.set(true, forKey: "SoundSwitch")
       soundSwitch = true

    }

If you are saving players money, name and all this other stuff, it would be better to save them in some kind of database. I'm not sure if you can do that with GameCenter.

A: The easiest way to save data you are working with on the device would be to use  NSUserDefaults. All you have to do is create a key, and store a value under that key. You can then use the key to access the value later and it is stored on the phone's permanent memory.
For example, you would use the user defaults to create a key called "eye color", store a value under that key, and then access it later using the term that you know the value is stored under (i.e. the key). This is a very simple way of storing such information.


text:
Q: Qual a diferença entre "git switch" e "git checkout"? Acompanho em alguns tutoriais e posts em redes sociais, exemplos de uso dos comandos do git e um deles foi o uso do git switch.
No exemplo que eu me deparei, apesar de não ter nenhuma explicação, foi feito a criação de uma branch nova usando o switch. Veja o exemplo:
git switch -c feature/post

Pelos testes que fiz, a flag -c é para criar uma branch nova. Esse comando é "similar" (pelo menos analisando por alto) ao comando git checkout -b feature/post para se criar uma nova branch.
Para relizar a troca de branchs, foi feito:
git switch master

Semelhante ao:
git checkout master

Confesso que é bem raro eu ver exemplos com uso do switch, mas creio que deva ter algo interessante para ser mencionado em relação ao checkout, então eu pergunto:

*

*Qual/quais a/as diferenças entre git switch e git checkout?

*Quando usar um ou outro? (se vem ao caso)

*São comandos equivalentes (sinônimos)?

*Algum deles é ou vai ser deprecated?

A: O git switch foi criado na versão 2.23.0 do Git (em 2019). As notas desta versão dizem o seguinte:

Two new commands "git switch" and "git restore" are introduced to split "checking out a branch to work on advancing its history" and "checking out paths out of the index and/or a tree-ish to work on advancing the current history" out of the single "git checkout" command.

Ou seja, é um comando novo criado, juntamente com o restore, com o objetivo de separar as funções "mudar para um branch" e "mudar o estado de um arquivo". Ambas as funções eram feitas pelo comando checkout, que fazia uma ou outra coisa dependendo do que você passava como parâmetros. Para acabar com (ou pelo menos diminuir) essa confusão, resolveram separar estas funções nos comandos switch e restore.
O switch, no caso, é para alternar entre diferentes branches (ou simplesmente "mudar de branch"). Ou seja, antes fazíamos git checkout branch para mudar para um branch, agora podemos fazer git switch branch. Ou ainda git checkout -b branch para criar o branch e já mudar para ele, agora podemos fazer git switch -c branch para fazer o mesmo.
Mas como já dito, o checkout acumulava funções. Por exemplo, se eu modifiquei um arquivo e ainda não fiz git add, eu poderia fazer git checkout arquivo para que as alterações fossem revertidas e ele voltasse como estava no último commit. Já git switch arquivo dará erro, pois switch só trabalha com branches (aliás, para trabalhar com arquivos foi criado o restore, ou seja, bastaria fazer git restore arquivo para obter o mesmo efeito do checkout).
Creio que a ideia de separar as funções é para deixar mais claro o que está sendo feito. Se estou mexendo com branches, uso switch. Se quero só mexer com arquivos, restore. Ter dois comandos separados, cada um com sua função específica, me parece mais claro do que ter um único comando que pode fazer um ou outro dependendo dos parâmetros.
Nesta resposta há uma tabela comparativa entre os comandos. Mas vale lembrar que - pelo menos hoje enquanto escrevo esta resposta - a documentação do git switch diz:

THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.

Ou seja, por enquanto é um comando experimental e o comportamento pode mudar em versões futuras.
Acredito que o git checkout não vai deixar de existir tão cedo. Mesmo que o git switch deixe de ser experimental, ainda deverá haver um período em que ele coexistirá com checkout, até por questões de retrocompatibilidade (pense em quantos scripts devem existir por aí que ainda usam checkout por exemplo).
Vale notar também que no commit que introduziu o comando switch tem o seguinte comentário:

The good old "git checkout" command is still here and will be until all (or most of users) are sick of it.

Ou seja, não me parece que o git checkout vai sumir tão cedo. O git switch foi criado em 2019, e na data de hoje a documentação (atualmente na versão 2.37.3) ainda não diz nada sobre ele ser removido ou ficar obsoleto.


text:
Q: Calling a child method from a button on a parent vue component I want to call the toggleDetails method of postDetails from the parent component's img tag and I don't seem to understand how to make it work.
Parent:

        <postDetails :post="post"></postDetails>

Child:
<template>

{{this.post.desc}}

</template>

A: If you only want to emit an event from parent to child, you can do something like this:
Parent component:
<postDetails
  ref="post"
  :post="post"
></postDetails>

methods: {
  toggleDetails () {
    this.$refs.post.toggleDetails()
  }
}

Child component:
methods: {
  toggleDetails () {
    this.isDetailsOpen = !this.isDetailsOpen
  }
}

But to be able to send events between any components you would have to create an eventBus (eventHub).


text:
Q: RESTlet startup initialization deprecated? I'm trying to use the restlet.org library to build a RESTful web interface, and I've noticed that unlike it's servlet counterpart, it has no complement to GenericServlet.init().
Short of building another servlet to do my startup logic, is there any built-in way to avoid building my database factories and the like on the first request (and all the commensurate locking I'll have to do to avoid multiple initializations)?

A: Are you wanting to run it in a servlet container?  If not, the documentation shows you how to run it stand-alone:
public static void main(String[] args) throws Exception {
    // Create a new Component.
    Component component = new Component();

    // Add a new HTTP server listening on port 8182.
    component.getServers().add(Protocol.HTTP, 8182);

    // Attach the sample application.
    component.getDefaultHost().attach("/firstSteps",
            new FirstStepsApplication());

    // Start the component.
    component.start();
}

You could certainly do the initialization there.
If you want to use the servlet approach, try writing a new servlet and extending theirs.  Implement your init method and call the one for the super class.

A: If you really want to do this in a servlet environment, you could potentially have two servlets within your webapp: one for the Restlet application/component and one for your initialization, using load-on-startup (which you wouldn't necessarily map to any URL, as far as I'm aware you don't have to). This way, you wouldn't have to subclass org.restlet.ext.servlet.ServerServlet. I think this is probably easier, since that init servlet would just contain init(), but this would only work for things that do not depend on the Restlet app/component to be initialized first.
<context-param>
    <param-name>org.restlet.clients</param-name>
    <param-value>HTTP HTTPS CLAP FILE</param-value>
</context-param>

<servlet>
    <servlet-name>ExampleInit</servlet-name>
    <servlet-class>example.TestInitServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet>
    <servlet-name>Example</servlet-name>
    <servlet-class>org.restlet.ext.servlet.ServerServlet</servlet-class>
    <init-param>
        <param-name>org.restlet.application</param-name>
        <param-value>example.TestApplication</param-value>
    </init-param>
    <init-param>
        <param-name>org.restlet.autoWire</param-name>
        <param-value>true</param-value>
    </init-param>
</servlet>

<servlet-mapping>
    <servlet-name>Example</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

Alternatively (or perhaps in complement to this), I tend to use JNDI for initializing the database connections and a few other configuration settings. This also allows me to keep the same configuration and loading mechanisms, whether I use a Restlet standalone server or Restlet within a webapp.
For example, for deployment within a servlet container (e.g. Jetty or Tomcat), I use the container's JNDI configuration, but for local tests (with a standalone Restlet app), I use the Jetty JNDI context factory (which you can get as a separate jar from the rest of Jetty).


text:
Q: Catching undeclared CheckedException I'm using a third-party java library and this library class has a method called doSomething:
Library.doSomething();

In the course of the doSomething method, it sometimes throws a java.net.SocketException, but the doSomething method does not declare the SocketException as a checked exception. So when I try to write:
try {
    Library.doSomething();
} catch (java.net.SocketException error) {
    error.printStackTrace(); // and do other recovery stuff
}

I get the following compiler error:
Unreachable catch block for SocketException. This exception is never thrown from the try statement body

However, I know that at runtime the doSomething method frequently throws the SocketException. I know that I can catch a generic java Exception and then check to see if it is a SocketException, but is there any more elegant way to catch the SocketExceptions thrown by this third party closed source library?
Thanks!
Edit - It turned out the SocketException is wrapped in a WebServiceException and I just missed the wrapped exception in a crowded error log. So there really isn't any question to answer. Sorry for the confusion.

A: You should write
catch (Exception e) {...}

Because compiler returns error if the catch block will never (or hardly ever) execute. In the catch block, you can compare the Exception using "instanceof" statement to get an information about specific exception.

A: Mena's answer is very good, but I just want to state that there are ways (4 of them if I recall correctly, I mention them in the comments) to throw check exceptions that are not declared.
As a solution I suggest catching something general like Exception and check the type of the caught exception (using instanceof is recommended).

A:
I know that I can catch a generic java Exception and then check to see if it is a SocketException, but is there any more elegant way to catch the SocketExceptions thrown by this third party closed source library?

There is no alternative that will actually deal with the exception; i.e. allow you to actually handle it in the normal fashion.
Basically, the 3rd-party library has broken Java's checked exception rules.  It is faulty and should be fixed.

FWIW, the code to work around the 3rd-party library bug is a "delicate":
try {
    callNastyMethod();
} catch (Exception ex) {
    if (ex instanceof SocketException) {
        // handle the exception we are expecting
    } else if (ex instanceof RuntimeException) {
        // unexpected runtime exceptions should be rethrown
        throw (RuntimeException) ex;
    } else {
        // deal with any other checked exceptions; for example.
        throw AssertionError("Unexpected checked exception", ex);
    }
}


text:
Q: Display time difference (6 hours ago) in a Soliloquy caption Thanks for viewing. I am using a soliloquy plugin addon to display post date in slide captions. I want to change the post date to human difference or 'hours ago' format. I'm converting get_the_date using the following in functions file
// Relative date & time
function wpse_relative_date() {
  return human_time_diff( get_the_time('U'), current_time( 'timestamp' ) ) . ' ago';
}
add_filter( 'get_the_date', 'wpse_relative_date' );

and the plugin is
function sol_soliloquy_fc_date_terms( $content, $post, $data ) {

    // Start Config
    $sliderSlugs = array(
        'your-slider-slug-name',
    );

    // Check slider ID is the one we want to amend
    if ( ! in_array( $data['config']['slug'], $sliderSlugs ) ) {
        return $content;
    }

    // Build date and taxonomy terms content
    $additional_content =

    '<div class="soliloquy-fc-date">'
        . __( '', 'soliloquy-featured-content-date-terms' ) . get_the_date( 'dS F Y', $post->ID ) . '
    </div>';

    // Return content
    return $content . $additional_content;

}
add_filter( 'soliloquy_fc_caption', 'sol_soliloquy_fc_date_terms', 1, 3 );

This outputs the amount of days the first post was created and all others are the same so I am guessing it's not returning each posts time because it's outside the loop. I'm a php newbie and I am guessing it's something to do with not being able to use the $post->ID inside the get_the_date.
Any help greatly appreciated!

A: In your filter function you should pass post ID to get_the_time() function, otherwise you will get the date from current post.
function wpse_relative_date( $date, $format, $post ) {
   return human_time_diff( get_the_time('U', $post), current_time( 'timestamp' ) ) . ' ago';
}
add_filter( 'get_the_date', 'wpse_relative_date', 15, 3 );

References:

*

*get_the_time() function

*get_the_date filter


text:
Q: Looking to 'hide' a window by sending it to background or 'detatching' it from another window I've compiled a little python program and it has this window open (cmd console) and I would like to make it a background task or just hide it from the user somehow.
Yes I am aware that I can compile my py files with --windowed, but that's off the table, as it is causes other problems.
I'm hoping for a solution in PowerShell, or Python. Any advice or suggestions are great as well.
And no, I cannot close it (it closes the application I want open)
the two windows in question:

A: Your two easiest options would be PowerShell and Windows Scripting Host.
If you want the windows scripting host version, please ask.
Powershell:
You use the Start-Process cmdlet with the flag -WindowStyle hidden.
For instance:
Start-Process -WindowStyle hidden -FilePath python.exe -ArgumentList "c:\my_py_path\my_py_file.py"
Remember, you will have no window to close.  To pull the plug, you will have to kill the task.

A: I know nothing of Python and can't make out the images you linked to, but PowerShell can hide any window you can obtain the handle to if you use Add-Type to Pinvoke the ShowWindow() function:
Add-Type @'
using System;
using System.Runtime.InteropServices;

public class API {

    public enum SW : int {
        Hide            = 0,
        Normal          = 1,
        ShowMinimized   = 2,
        Maximize        = 3,
        ShowNoActivate  = 4,
        Show            = 5,
        Minimize        = 6,
        ShowMinNoActive = 7,
        ShowNA          = 8,
        Restore         = 9,
        Showdefault     = 10,
        Forceminimize   = 11
    }

    [DllImport("user32.dll")]
    public static extern int ShowWindow(IntPtr hwnd, SW nCmdShow);
}
'@

Copy, paste, and execute the above code in a PowerShell window (or script) and the window can then hide and show itself like so:
$ThisWindow = [System.Diagnostics.Process]::GetCurrentProcess().MainwindowHandle
[API]::ShowWindow($ThisWindow,'Hide')
sleep -Seconds 5
[API]::ShowWindow($ThisWindow,'Show')

The handles to other top-level windows can be obtained from Get-Process or Pinvoking the FindWindow() functions.


text:
Q: Cannot connect to Coinbase Extension via the @web3-react/walletlink-connector I am trying to connect to the coinbase extension via the wallet link connector's instance, new WalletLinkConnector, but I cannot even get the extension's popup open. I am following the exact tutorial on the official docs. The connection with the metamask works fine but it fails with the coinbase. Here is the screenshot of the error I am getting in console.log

Here is the connector code I am using

export const Walletlink = new WalletLinkConnector({
  url: "https://rinkeby.infura.io/v3/<my-api-key>",
  appName: "demo",
});

I am calling this WalletLink via the activate method of the useWeb3React(). Any solution will be greatly appreciated.

A: This maybe happen in non https websites in my experience.
Did you try to connect in SSL website (https)?


text: Q: Make bootable partition from a Live CD I have a dual-boot system with Ubuntu 15.10 and Windows 10, behind GRUB2. I'd like to add a separate bootable partition that I can use for partition editing and recovery tasks. I've downloaded the GParted Live CD and created an empty partition, but how can I put the GParted .iso on it and make it bootable from GRUB?


text:
Q: Is there a way to hide header title for react-navigation-drawer component I'm making an app using react navigation-drawer for native, and I was wondering if it is possible to hide just the header title without hiding other things with for example
headerShown: false

A: Yes, you can pass an empty string just like this
options={() => ({
          headerTitle: "",
 })}

A: EDIT: I found the way to do it in options property of drawer screen you can set the headerTitle to ''
<Drawer.Screen name="Home" component={Home} options={{title: 'Home', headerTitle:''}}/>

the title is the name of the Screen shown in the drawer menu, and the headerTitle is of course the one shown on the top of the screen, on the header


text:
Q: How can you run only one class in a package and among several runnable classes? I have few classes include Java JFrame forms and java class.
I want to do something so that the Java class runs only and the forms run by that class. (I have coded the last item).
What can I do now?


text:
Q: wordpress excerpt execute shortcode? I'm new in wordpress.
So, i create shortcode to get data in functions.php and use it in post.
function create_shortcode_test {
.....
return my_data;
}
add_shortcode ( 'test_shortcode' , 'create_shortcode_test' );

[test_shortcode]

And i use excerpt for post.
example

In homepage, i can see excerpt.
After open post, i can see data get with shortcode.
But i want to know:
In homepage post show excerpt and shortcode working
or post just show excerpt, shortcode not working. And after open post shortcode working.
That mean i want to know, if i choice show excerpt, in homepage (just see excerpt), shortcode in post (not in excerpt) working or not working () in homepage ?

A: You can use this simple method to display the_excerpt as this tag comes under the loop..
function create_shortcode_test {
    <?php if ( have_posts() ) : ?>
        <?php while ( have_posts() ) : the_post(); ?>
        <?php the_excerpt(); ?>
        <?php endwhile; ?>
    <?php endif; ?>
    }

add_shortcode ( 'test_shortcode' , 'create_shortcode_test' );


text:
Q: Displaying pdf in WinForms webbrowser control under x64 I have an application that uses the webBrowser control provided by Microsoft to display a pdf to the user. It has been found that when the application is running under x64 the pdf will download and open in Adobe Reader and not display in the user control. (Reference: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/06ad960b-7c5e-459c-9261-ca9d0e4ac88f/) Has anyone found a workaround for this issue other than compiling the application in x86?

A: That's to be expected; the 32bit PDF Reader Document Object is only loaded by the 32bit browser. When it's not there, you go down the normal file download codepath.
See also: http://blogs.msdn.com/b/ieinternals/archive/2010/01/13/web-browser-control-does-not-show-flash-or-silverlight-in-a-64bit-dot-net-application.aspx


text:
Q: Appending to a string macro I have a program that offers different functionality depending on compile time definitions. I defined OPT_STRING that holds all possible command line arguments (for use with getopt_long). I've been looking for a clever to change the definition of it depending on compile time definitions. I've came up with this:
#define OPT_STRING "haspvb"

#ifdef HAVE_WIFI
#define OPT_STRING OPT_STRING "mw" // => "haspvb" "mw"
#endif // HAVE_WIFI

#ifdef HAVE_IMEI
#define OPT_STRING OPT_STRING "i" // => "haspvb" "mw" "i" or "haspvb" "i"
#endif // HAVE_IMEI

However, this results in a compilation error:
error: "OPT_STRING" redefined

Is there some kind of "macro magic" to achieve what I'm trying to do?

A: You can't "append" to a macro, it's simply not possible.
As a possible solution you could define different macros, and then use them together to define the final OPT_STRING macro:
#define OPT_STRING_BASE "haspvb"

#ifdef HAVE_WIFI
#define OPT_STRING_WIFI "mw"
#else
#define OPT_STRING_WIFI
#endif // HAVE_WIFI

#ifdef HAVE_IMEI
#define OPT_STRING_IMEI "i"
#else
#define OPT_STRING_IMEI
#endif // HAVE_IMEI

#define OPT_STRING (OPT_STRING_BASE OPT_STRING_WIFI OPT_STRING_IMEI)


text:
Q: change auto-complete option inside its select method Here's my code:
$authorizedRow = $('.authorizedRows').html()

$("#name").autocomplete({
        source: "userlookup.cfm",
        minLength: 3,
        select: function(e, ui) {
            $('#email').last().attr('value',ui.item.mail).attr('disabled','disabled');
            $('#phone').last().attr('value',ui.item.phone).attr('disabled','disabled');
            $('.authorizedRows').last().append('<button class="deleteRow">x</button>');
            $('.deleteRow').button();
            $('#people').append('
' + $authorizedRow + '
').autocomplete( "option", "appendTo", "#name");
        },
        change: function(e, ui) {
            if (a) {
                //not used yet
            }
        }
    });

So, what I'm trying to do is have this auto-complete on an input field, when a user selects it will autofill two other fields. These three fields (the name, phone, and email) are all contained in my authorizedRows div. It will append a button at the end of the 'last' authorizedRows div, then it will append a whole new authorizedRows div at the end of the 'people' div.
Where my problem is at is after the new row appends, the auto-complete will not work on the new name field in the new row. This is because the event-listener has not attached to the DOM element yet.
I tried to solve this by using the .autocomplete('option') on the people div selector, as you can see. It didn't work. Any ideas how I can get the auto-complete to work on my dynamically created field? Thanks.

A: I solved it using a class selector instead of id.
EDIT:
jQuery selectors of IDs will return just the first one if there is more than one, that is why the event didn't attach to the other dynamically created fields. jQuery selectors of class will return an array for every class that matches the selector.


text:
Q: React too many re-renders error when trying to use 'useState' I am getting the following error:

This is the component code snippet causing the error:
const EditDetailsModal = ({show, handleClose}) => {

    const name = useSelector(selectors.getName)
    const email = useSelector(selectors.getEmail)
    const phoneNumber = useSelector(selectors.getPhone)
    const country = useSelector(selectors.getCountry)
    const key = "AIzaSyCda4pqQF5xcyDAfA7gt61jVXcaeKeES44";
    const [newName, setNewName] = React.useState();
    setNewName(name);
    function handleChange(e) {
      setNewName(e.target.value);
    }

    return (
          <Modal show={show} onHide={handleClose} className="editModal">
                <FormContainer>
                    <Modal.Header className="editModalHeader" closeButton>
                      <Modal.Title>Edit Personal Details</Modal.Title>
                    </Modal.Header>
                    <Modal.Body>
                        <Form>
                          <Form.Group controlId="formBasicName">
                            <ModalTextInput customPlaceholder="Name" value={newName} onChange={(event) => handleChange(event)}/>
                          </Form.Group>

Would be grateful if you could help me identify what is causing this.

A: You're calling setNewName everytime it re-renders, updating newName causing another render, resulting in an infinite re-renders,
remove setNewName call, and set the initial value like React.useState(name);
const [newName, setNewName] = React.useState(name); // set the initial value of newName

// setNewName(name); // remove this line
function handleChange(e) {
  setNewName(e.target.value);
}

...

A: setNewName(name);
    function handleChange(e) {
      setNewName(e.target.value);
    }

there is no need to call setNewName(name); above the handleChange function. just delete it


text:
Q: Zombies on starting resque & resque-scheduler Since upgrading my stack to Debian Squeeze, RVM 1.7.2, Ruby 1.9.2, and Rails 3.1rc6 (All gems are latest version) I see strange behavior: After rebooting the machine and starting redis/nginx etc. I start resque-scheduler with
rake resque:scheduler &

After that I'll start at least one worker with:
QUEUES=printing,mailing rake environment resque:work &

The moment I start one of these rake processes I get two zombies in my ps-list like this:
1222 pts/3    Sl     0:12 resque-scheduler-2.0.0.d: Schedules Loaded
1236 pts/3    Z      0:00 [ruby] <defunct>

This in itself is only a cosmetic issue, but resque and it's web front end don't behave like expected any more; e.g. I can only see some of the workers as active and working in the web front end.
Any ideas on how to make resque behave itself again?


text:
Q: Error message still showing up on successful user input Ok with the help of stackers I was able to get an error message to show up below input form.
What I need is the error message to not be displayed when the user enters in any input in the form. What am I doing wrong?
Heres the HTML
<form id="url">
        <input type="text" name="urlName">
        <input type="submit" value="Build Your App"></input>
    </form>

Heres the JS
document.getElementById("url").addEventListener("submit", (event) => {
            event.preventDefault()
            let errorMessage = document.getElementById("error-message").innerHTML = "Please provide your store URL";
            let myForm = document.getElementById("url");
            let formData = new FormData(myForm);
            if (formData.get("urlName") === "")
            return errorMessage;
            EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
            newUrl = redirectLink(EndOfUrl);
            window.location.href = newUrl;
            return false;
        });

    function sanitizeDomainInput(input) {
        input = input || 'unknown.com'
        if (input.startsWith('http://')) {
            input = input.substr(7)
        }
        if (input.startsWith('https://')) {
            input = input.substr(8)
        }
            var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
            return regexp.test(input) ? input : 'unknown.com';

    }

    function redirectLink(domain) {
        return `https://dashboard.getorda.com/signup/?state=${domain}`;
    }

A: *

*You are assigning the error message to the error message container div regardless of if there's an error which is causing the message to appear in ANY case.

*Refer below snippet where I've moved the error message assignment inside the error condition.

document.getElementById("url").addEventListener("submit", (event) => {
  event.preventDefault()
  let errorMessage = "Please provide your store URL";
  let myForm = document.getElementById("url");
  let formData = new FormData(myForm);
  if (formData.get("urlName") === "") {
    document.getElementById("error-message").innerHTML = errorMessage;
  }
  EndOfUrl = sanitizeDomainInput(formData.get("urlName"));
  newUrl = redirectLink(EndOfUrl);
  window.location.href = newUrl;
  return false;
});

function sanitizeDomainInput(input) {
  input = input || 'unknown.com'
  if (input.startsWith('http://')) {
    input = input.substr(7)
  }
  if (input.startsWith('https://')) {
    input = input.substr(8)
  }
  var regexp = new RegExp(/^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$/)
  return regexp.test(input) ? input : 'unknown.com';

}

function redirectLink(domain) {
  return `https://dashboard.getorda.com/signup/?state=${domain}`;
}
<form id="url">
  <input type="text" name="urlName">
  <input type="submit" value="Build Your App"></input>
</form>


text:
Q: Solution of Poisson equation for $f(x,y)=1$ Consider Poisson equation
$$
\Delta u=f
$$
To be more specific,
$$
\frac{\partial^2u}{\partial x^2}+\frac{\partial^2u}{\partial y^2}=f(x,y)
$$
What would be the analytical(Exact) solution of the above equation for $f(x,y)=1$?
Assume that the domain is $\Omega=(-1,1)\times (-1,1)$ and the boundary conditions are of Dirichlet type, i.e, $u(x,y)=g(x,y)$ on $\partial \Omega$.
$g(x,y)$ is a general function as stated.

A: The Green's function for $\Omega = (-1,1)^2 \subset \mathbb R^2$ is $$G((x,y),(\zeta,\eta))= \frac 4 {\pi^2} \sum_{k,\ell=1}^\infty \frac{\sin \big ( \frac{k\pi x}2 +\frac{k\pi } 2 \big )\sin \big ( \frac{k\pi \zeta}2 +\frac{k\pi } 2 \big )\sin \big ( \frac{\ell\pi y}2 +\frac{\ell\pi } 2 \big )\sin \big ( \frac{\ell\pi \eta}2 +\frac{\ell\pi } 2 \big )}{k^2+\ell^2} . $$ Hence, $$u(x,y) = - \int_{\partial \Omega}g(\zeta,\eta) \frac{\partial G}{\partial \nu}((x,y),(\zeta,\eta)) \, d S(\zeta,\eta)
 - \int_\Omega G((x,y),(\zeta,\eta)) \, d \zeta d \eta$$ where $\nu$ is the outward pointing unit normal to $\partial \Omega$ and $$\frac{\partial G}{\partial \nu}((x,y),(\zeta,\eta)) := \nabla_{(\zeta,\eta)} G((x,y),(\zeta,\eta)) \cdot \nu(\zeta,\eta). $$ Via some large (but elementary) calculations you should be able to work out each of the terms involving $G$.


text:
Q: change a group_var on every 20 executions I have an Ansible project with more or less 100 hosts (much more in a near future), this project does several calls to an API that as a limit rate of 1000 calls per token.
In my project I define the token on group_vars and what I want is to run a task and have the token changed every 20 hosts, like the first 20 hosts would have the group_var token=A, the next 20 hosts would have the group_var token=B, etc ...
Is there any way to do this ? I took a look on loop docs but it seems that all loops are meant to run multiple variables on each host and that's quite the opposite of what I'm trying to achieve.


text:
Q: Understand Flash/Actionscript to create app with many pages iam planning to create a photo/video gallery secured by a pin.
So i plan to have 4 pages, Login, Menu, Image Page and Video View.
Login would be a simple textbox where i check the pin.
The Menu would show all picture albums and videos in a list i create with clickable sprites or buttons or something like that. And a video view where a video will be shown if i click on a video link on the menu page.
I tried to prepare the scene in flash cs5, so i decided to create 4 frames. ALl pages have their own layer. The first will be the login, second the menu, third the image view (incl. thumbnail show and fullscreen view popup) and a video view. On each keyframe i put a rectangle converting it into a MovieClip acting as the main container where all the stuff will come into.
Now i tried to initialize all these MovieClips by resizing them everytime the stage is resized. For this i get errors, that some of the MovieClips are null. This is because the MovieClips exist only keyframe 2 for the menu or keyframe 3 for the image page and keyframe 4 for the video view. So i have to put them all into keyframe 1 to be able to access. But i created 4 keyframes because i want to jump to them by using "gotoAndStop( n)", where n stands for keyframe 2, 3 or 4.
I dont get it, how does Flash interpret the code and how is the visibility of these MovieClips. Can i only access the MovieClip from keyframe 2 because i added it on keyframe 2 only? What is the best solution to have a simple 4 page app where on page 1 (menu) i click on video link which holds some sort of ID of the video, then i jump to keyframe 4 for the video view providing it with that ID, but how to do that when Actionscript doesnt even know there is a video container MovieClip. To get Actioscript to know all of them, i  have to move them to keyframe 1, but then how to do the paging stuff.
Look at the following screenshot from my project. It shows the timeline, with the 4 keyframes. As you see each layer has 4 frames, but only 1 keyframe for the MovieClip. I think i dont need to add 4 keyframes, do i?

I did a simple photo gallery before, but i used only one keyframe doing all the stuff in it, so i didnt have any problem when accessing all the MovieClips as i didnt need to do any jumping/paging. I would like to seperate each page having them on a seperate keyframe but being able to access the stuff in it via Actionscript. Did i misunderstood the way Actionscript is working??
Thanks in advance.

A: I would stop using multiple frames (only have 1) and throw each of my "pages" in their own MovieClip. Then I would either make only my current page loginPageInstanceName.visible = true and the rest menuPageInstanceName.visible = false, etc... when needed, or even initialize each page movieClip as needed.
Personally, having code in multiple frames drives me nuts. I would have all code that effects things at the top level in only one place, preferably in a custom document class for your swf, alternatively in the top layer of frame one, like your "Action" layer. I would then throw code specific to each "Page" in it's own class, either within it's "export to actionscript" defined class or in the same manner as your top level code in the "Action" layer of the respective MovieClip.
I hope that helps.

A: Short answer,
first create a movieClip() then click inside of it delete its contents now start making the same thing again on that timeline but put all your code on the main timline and refer to the instance name for example
  AllmyClips.gotoAndStop(1);
  // allMyClips is the instance name

  if(allMyClips.textbox1.text == "bob" && allMyClips.passwordbox.text == "thispassword"){
      AllmyClips.gotoAndStop(2);
    }

Its That easy just button1.addEventListners and throw the above in a function();
now all of viarbles can be global and easy to function if you can upload the fla somewhere and i will fix it for you, im bored so no problems and you shouldnt have large invisible clips in the background


text:
Q: Does this Jquery plugin always return an array? I am using this plugin for photo face detection.  It works, but when there is no detectable face in a picture, the error function is not called.  The "complete" function is called instead.
I figure when it fails to detect a face, it returns no array, or returns undefined objects, or null, or something, so I've tried:
//also tried null this way
if(typeof coords[i].confidence === 'undefined') {
alert("you have little aptitude for programming.");
}

if(coords instanceof Array) {

        alert("good job!!");
} else {
alert("not even close!!");
}

if(!(coords.length)) {
alert("you have a distorted perception of your own abilities.");
}

if (positionX > coords.length) {

alert(coords[i].confidence);
}

When a face is detected it displays the appropriate alerts, but when no face is detected, no alert is displayed.  It just calls the "complete" function.
Here is the script.  Let me know if I should provide more code.

TRY IT NOW!

A: complete is indeed invoked regardless of success. In case of a failure to detect any faces plugin returns empty array and that is why you don't see any alerts. Your for loop is not executed.


text:
Q: How to embed the Layout in managed package We have developed the managed app and now its ready to deploy to app exchange market, I want to know that how we can deploy the layout?
In standard page layout we have added the visualforce page and how I can do this in installed org?

A: To verify your question, I created an unmanaged package and added a custom object to the package. As a result, salesforce automatically included following components

*

*List View

*Custom Fields

*Validation Rule

*Standard Page layout (Default)

*Visualforce Pages, if included in the layout

It will follow the same behavior for manage package as well.

Update -

You will have to explicitly add Standard Page Layout for standard Objects. However it will automatically include related page

Page layout ->    Actions, custom buttons, custom links, s-controls, and
  Visualforce pages

More Details : https://developer.salesforce.com/docs/atlas.en-us.packagingGuide.meta/packagingGuide/packaging_components_auto_added.htm

A: It is advisable not to modify standard layout for standard objects and package standard layout.The reason for this may be different customers mmay have different fields set on their standard layout and you don't want to override them with yours.
The best strategy are
1)Add in the set up guide which will teach them how to configure your component in standard page layout for standard object.Make a video tutorial of set up.
2)Provide a custom page layout with inline vf configured and explain customers consequence of using that


text:
Q: Is it possible to debug an app with a device connected on a remote network? There's an app my team is developing in Android Java using Android Studio.
The app works alright on all our test devices, however it shows some bugs on the client's device.
Is it possible to somehow connect the client's device to his network and make this device available on a developer machine for debugging over the internet?
It was pointed to me that this answer already answers my question. I agree that it does in part; it teaches how to connect the client adb to the adb server on a remote network. Still, can I use Android Studio to debug the phone?
Maybe VPN can be used? I don't know much about VPNs, so suggestions of which would work would be awesome.
Thank you.

A: This is pretty dangerous, as exposing the debugging bridge of your personal device to the internet could prove problematic and unsafe for your personal data.
That aside, the only way I could see this working would be if the client were to port forward the debugging port to the IP address of their device (this would need to be completed on their router)
By default I believe the port to be 5037.
Once the port is forwarded, you should be able to connect to that device in particular by using
adb connect <their external IP>

Again, I cannot stress enough how dangerous this could potentially be.


text:
Q: Mouse pointer hiding in Kotlin's Jetpack Compose for Desktop I need to create a GUI running on Raspberry PI 4B connected to a touch screen. When the app is running I would like the mouse pointer to be hidden since it's not needed on such type of screens.
I've read I can add a nocursor option as follows xserver-command = X -nocursor in the file /etc/lightdm/lightdm.conf. Now I am not able to verify that since my RPI hasn't been shipped yet. Also I wouldn't like to hide the pointer completely on the OS but rather only when the app is running.
I couldn't find anything interesting either in the documentation of Compose or source classes itself that's why I am asking here.


text:
Q: How to check if string is of type ObjectId in Node.js I have a route /api/:id where :id has to be of type ObjectId.
Because following is the query I am runnuing
const data = await Person.find({_id:req.params.id})

It works fine if :id is of type ObjectId but if user explicitly runs the api lets say /api/anything, then Mongoose throughs an error

CastError: Cast to ObjectId failed for value "anything" at path "_id"

So, I would like to check if req.params.id is of type ObjectId and perform further operations only if it is.
Thus code would look like
if(checkObjectId(req.params.id)) {
const data = await Person.find({_id:req.params.id})
}

A: Use the Mongoose functionality:
if(mongoose.isValidObjectId(req.params.id)) {
  const data = await Person.find({_id:req.params.id})
  ...
}

Mongoose.prototype.isValidObjectId()
Returns true if Mongoose can cast the given value to an ObjectId, or
false otherwise.
mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
mongoose.isValidObjectId('0123456789ab'); // true
mongoose.isValidObjectId(6); // false

A: you can use isValid method for validate object id

mongoose.Types.ObjectId.isValid('63d632828e944c3a08f15925')

A: Why if when you can use try ... catch
let data;
try {
    data = await Person.find({_id:req.params.id})
} catch(err) {
    console.log('Error retrieving data (Person):', err);
}


text:
Q: Hive External table not showing anything I am trying to learn Hive by following twitter data tutorial from the below link.
https://github.com/cloudera/cdh-twitter-example/
I have successfully installed and configured hadoop and hive and tested simple text file load into hive table. All working good so far.
However, even thought files existed in hdfs, external table is showing nothing.
I used the below code to create tables.
CREATE EXTERNAL TABLE (
...
 Columns ....
...
)
PARTITIONED BY (datehour INT)
ROW FORMAT SERDE 'com.cloudera.hive.serde.JSONSerDe'
LOCATION '/user/flume/tweets';

I think where the problem comes in is the folder structure in my hdfs ..
it's currently follows year/month/day/hour/ like below.
/user
  -- /flume
      -- /tweets
          -- /2015
              -- 04
                -- 01
                 -- 13
                 -- 14
                -- 02
                 -- 15
                 -- 16

Is there a way to set the partition correctly for this folder structure when creating external table in Hive ?
Thanks in advance for your help...

A: You have to add the partition to the table.
  ADD JAR   your-serde-jar-file-path.jar

  ALTER TABLE tweets ADD IF NOT EXISTS PARTITION (datehour = 2015040113) LOCATION '/user/flume/tweets/2015/04/01/13';

-you have to pass  datehour and partionpath form oozie cord file.
 ADD JAR ${JSON_SERDE};

ALTER TABLE tweets ADD IF NOT EXISTS PARTITION (datehour ${DATEHOUR}) LOCATION '${PARTITION_PATH}';

Please refer it
  http://blog.cloudera.com/blog/2013/01/how-to-schedule-recurring-hadoop-jobs-with-apache-oozie/


text:
Q: Always get a Security Error for Internal HTTPS Website Full disclosure, I asked this question over at Ask Different (https://apple.stackexchange.com/questions/96776/always-get-a-security-error-for-internal-https-website) but didn't get much helpful feedback. I'm hoping this question fits better here.
My company recently changed an internal site to use HTTPS instead of HTTP (it is our Jira site in case that matters). From what I can tell, this site is using an internal certificate. On our work computers this certificate appears to be pre installed so the website comes up without trouble in IE, Firefox, and Chrome. However, my personal computer is a Mac (OS X 10.8.4) and I am having major troubles accessing the site through any browser. I have followed instructions to install the certificate in my Keychain and I believe I have successfully done that, but I am still not able to access the site.
When Accessing the site I Get:
Chrome: Invalid Server Certificate You attempted to reach jira.surescripts.local, but the server presented an invalid certificate.
Safari: Safari can't open the page Safari can't open the page "https://jira.local:8081/" because Safari can't establish a secure connection to the server "jira.local"
In Chrome when I view the certificate information it I see: Intermediate certificate authority. Expires: Thursday, May 21, 2015 1:19:28 PM Central Daylight Time. This certificate is valid
To make sure that it wasn't something strange with our company's VPN, I installed a Windows 7 virtual machine on my Mac and installed the certificate in Windows and am able to successfully log on to the site how I always would.
I am not much of an expert with certificates and I really don't know where to go from here. Any help would be greatly appreciated! Thanks.


text:
Q: Cyclic Subgroups of U(n) from http://abstract.ups.edu/aata/exercises-cyclic.html (problem 13):
"For n≤20, which groups U(n) are cyclic? Make a conjecture as to what is true in general. Can you prove your conjecture?"
where U(n) is the group of natural numbers < n and co-prime to n, under the operation of multiplication (mod n)
I find that U(n) is acyclic for n = 8,12,15,16,20, but unable to form a conjecture.


text:
Q: How to make a stored procedure accessible by a specific user I am using SSMS 10.50 to access SQL Server 2008 R2 and I am very new to SQL coding. My login id is SA. I created a stored procedure and I want to make it executable by specific users. But I am failing to do so.
When I write these line,
create proc GetCustomerDetailsCompanyWise
    (@comp varchar(40))
as
begin
    grant execute on GetCustomerDetailsCompanyWise to [sgp\deepak.b]
    execute AS USER='sgp\deepak.b';

    select *
    from DD_Customer
    where Company = @comp;
end

exec GetCustomerDetailsCompanyWise 'Google'

I get this error
Msg 916, Level 14, State 1, Procedure
GetCustomerDetailsCompanyWise, Line 6
The server principal "sgp\deepak.b" is not able to access the
database "TEMP" under the current security context.

Could you please explain what I may have done wrong and how can I fix it ?

A: First create the procedure
create proc GetCustomerDetailsCompanyWise
    (@comp varchar(40))
as
begin
    select *
    from DD_Customer
    where Company = @comp;
end
go

Then grant permissions
grant execute on GetCustomerDetailsCompanyWise to [sgp\deepak.b];
go

Then try to run it.

A: Add REVERT; before the end to get back to previous user state. Then remove grant statement from SP. Then create SP. Then run this:
grant connect on TEMP to [sgp\deepak.b];
grant select on TEMP to [sgp\deepak.b];
grant execute on GetCustomerDetailsCompanyWise to [sgp\deepak.b];


text:
Q: Redshift - Adding timezone offset (Varchar) to timestamp column as part of ETL to Redshift, in one of the source tables, there are 2 columns:
original_timestamp - TIMESTAMP: which is the local time when the record was inserted in whichever region
original_timezone_offset - Varchar: which is the offset to UTC
The data looks something like this:
original_timestamp      original_timezone_offset
2011-06-22 11:00:00.000000    -0700
2014-11-29 17:00:00.000000    -0800
2014-12-02 22:00:00.000000    +0900
2011-06-03 09:23:00.000000    -0700
2011-07-28 03:00:00.000000    -0700
2011-05-01 01:30:00.000000    -0700

In my target table, I need to convert this to UTC (using the offset). How do I do it?
So far I have tried multiple things but dateadd() seems to be the closest solution. But the problem with dateadd() is, when I say:
SELECT original_timestamp, original_timezone_offset
 ,dateadd(H, original_timezone_offset, original_timestamp) as original_utc_time

it is adding/subtracting '700'/'800' hours instead of 7/8 hrs to the original timestamp because the offset is a VARCHAR and the values are like: -0700 etc.
Did anyone see this issue before? Appreciate any help/inputs. Thanks.

A: Just take the 'hours' part of the offset:
WITH t as (
SELECT  '2011-06-22 11:00:00.000000'::timestamp as original_timestamp, '-0700' as original_timezone_offset
UNION ALL
SELECT '2014-11-29 17:00:00.000000'::timestamp,'-0800'
UNION ALL
SELECT '2014-12-02 22:00:00.000000'::timestamp,'+0900'
)
SELECT
  original_timestamp,
  original_timezone_offset,
  DATEADD(hour, SUBSTRING(original_timezone_offset, 1, 3)::INT, original_timestamp)
FROM t

2011-06-22 11:00:00 -0700   2011-06-22 04:00:00
2014-11-29 17:00:00 -0800   2014-11-29 09:00:00
2014-12-02 22:00:00 +0900   2014-12-03 07:00:00

You'll need some additional fancy code if you have non-full-hour offsets (eg +0730).

A: First, recognize that if your timestamps are already in local time of the given offset, then you need to subtract that offset to convert back to UTC.  In that first example you gave, 2011-06-22 11:00:00 -0700 is equivalent to 2011-06-22 18:00:00 UTC.
However, rather than try to add or subtract these values yourself, you should let the AT TIME ZONE function do the work for you.  It will create a timestamptz that is in your supplied offset, then you can use it again to convert to UTC.
(Note that you could use the CONVERT_TIMEZONE function instead, but that one is only understood by Redshift, where AT TIME ZONE works on regular PostgreSQL also.)
However, you have is that the time zone offsets you have aren't in a format understood by these functions.  See time zone usage notes.  So, before we try to convert, let's translate your offset strings to an understood format.
We will want -0700 to become +07:00.  The colon is required, and the sign must be flipped because it will be interpreted with the POSIX-style time zone format.  In that format, positive values lie west of GMT instead of the usual conventions specified in ISO 8601.
concat(translate(substring(original_timezone_offset, 1, 3), '-+', '+-'),':',substring(original_timezone_offset, 4, 2))

Then we will use that with AT TIME ZONE to do the conversion:
(original_timezone AT TIME ZONE <the above mess>) AT TIME ZONE 'UTC' AS utc_timestamp

Putting it all together...
WITH t as (
SELECT  '2011-06-22 11:00:00.000000'::timestamp as original_timestamp, '-0700' as original_timezone_offset
UNION ALL
SELECT '2014-11-29 17:00:00.000000'::timestamp,'-0800'
UNION ALL
SELECT '2014-12-02 22:00:00.000000'::timestamp,'+0900'
)
SELECT
  original_timestamp,
  original_timezone_offset,
  concat(translate(substring(original_timezone_offset, 1, 3), '-+', '+-'),':',substring(original_timezone_offset, 4, 2)) as modified_timezone_offset,
  (original_timestamp AT TIME ZONE concat(translate(substring(original_timezone_offset, 1, 3), '-+', '+-'),':',substring(original_timezone_offset, 4, 2))) AT TIME ZONE 'UTC' AS utc_timestamptz
FROM t

Output:
2011-06-22 11:00:00  -0700  +07:00  2011-06-22 18:00:00
2014-11-29 17:00:00  -0800  +08:00  2014-11-30 01:00:00
2014-12-02 22:00:00  +0900  -09:00  2014-12-02 13:00:00

SQL Fiddle here.


text:
Q: Why might a php script run slower in sequence than in separate parts? I've run into a weird problem, and hope that someone can help me out.  I've written a multiCurl spider in PHP that scrapes keywords off websites, and I'm running into a strange performance problem.
When I run the spider to scrape the first few levels of a site, it takes about 2 minutes to complete, which isn't that big a problem for my purposes.  What's strange is that when I try to run one spider after another in the same script, the runtime balloons for some reason.  For example, when I want it to sequentially run on 7 sites, I'd expect it to take 14 minutes (2 minutes per site), but instead it's taking upwards of 45 minutes to run.  I've tested each of the sites separately and they are in fact averaging at 2 minutes or below apiece, but when run in sequence it takes almost an hour.
I thought it might be something to do with memory issues, so I implemented APC cache to store the keyword data while the script is running. The thing is, when I look at my task manager (I'm running XAMPP on Windows 7) the Apache Server doesn't seem to go much higher than 46K/23% of the CPU, and everything else on my compy runs just fine.
I've taken a close look and made sure all the appropriate handlers are closed as soon as possible, large variables are unset/cached, and yet I'm still scratching my head as to why it's taking 3 times longer than expected to run one site after the other.  I'm about to go the route of trying to fork the spiders to separate processes using pcntl (I'm going to try a thumb drive install of linux), but I was wondering if anyone might have any ideas of what might be giving my application the performance hit.  Thanks!


text:
Q: Code sign Error on xcode 4.3.2 and ios 5.1 I create a demo application on my mac pc with the xcode 5.1.When i try to create a release build i am getting this error
 codeSign error :code signing required for product type 'Application' in SDK 'IOS 5.1'.

I already create the required certificates for the system.
Please help me out.

A: try this: Select right code sign that match your bundle id.


text:
Q: How can I render a single column table with an array of objects using dataTables? I have a single column table that displays 10 results per page using datatables 1.9.4. The table is being populated by the dataTable ajax method. I can render one value per row but I will need to be able to render multiple values per row. (Think 1 row = 1 array in the json object.)
How can I take an array of objects and render that array of objects into a single column?
I've read up on column rendering and object arrays. I'm having no luck.
e.g.
A row, once rendered, would look like this:

        Email Product

Product1

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi, a, similique, fugit, ratione facere eius mollitia quo illo quos minus laborum suscipit vel nesciunt totam debitis? Nihil, rerum non sed.

Here's what my data looks like (trimmed down):
{
    data: [
        {
            product_email: "email@email.com",
            product_name: "Product1",
            priduct_description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi, a, similique, fugit, ratione facere eius mollitia quo illo quos minus laborum suscipit vel nesciunt totam debitis? Nihil, rerum non sed."
        },
        {
            product_email: "email@email.com",
            product_name: "Product2",
            priduct_description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi, a, similique, fugit, ratione facere eius mollitia quo illo quos minus laborum suscipit vel nesciunt totam debitis? Nihil, rerum non sed."
        },
        {
            product_email: "email@email.com",
            product_name: "Product3",
            priduct_description: "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi, a, similique, fugit, ratione facere eius mollitia quo illo quos minus laborum suscipit vel nesciunt totam debitis? Nihil, rerum non sed."
        }
    ]
}

Here is my call to dataTables
this.$el.find('table').dataTable({
    sDom: '<"top">rt<"bottom"<"showing"i><"product-length"l><"product-pagination unlist horizontal"p>><"clear">',
    sPaginationType: 'full_numbers',
    oLanguage: {
        oPaginate: {
            sFirst: '<<',
            sLast: '>>',
            sNext: '>',
            sPrevious: '<'
        }
    },
    bProcessing: true,
    bServerSide: true,
    sAjaxSource: 'products.php',
    /*columns: [
        { data: '[]' }
    ],*/
    fnServerData: function(sSource, aoData, fnCallback) {
        console.log(sSource, aoData, fnCallback);
    }
});

A: You can try something like this:
$(document).ready(function(){
$("#Tabla").html("

Email	Name	Action

");
   $("#Tabla").dataTable({
     "aaData": arreglo,
     "aoColumns": [

      { "mData": "product_email" },
      { "mData": "product_name" },
      {
        "mData": null,
        "mRender": function (data, type, full) {
         var nombre =  full.product_email ;
         var a2 = '
'+full.product_name+'
';
         var desc = '
'+full.priduct_description+'</d>';
        return 'Email Product ' + a2 + desc;
      }
    }
                  ],
        "bDestroy": true
        }).fnDraw();

});

Working fiddle: http://jsfiddle.net/robertrozas/3kPVT/4/


text:
Q: Why can't I chmod these files that I could earlier? I was trying to add execute permissions to sh files in a folder. For that I mistakenly used:
find . -print0 -iname '*.sh' | xargs -0 chmod -v 744
and the output was :
mode of `.' changed from 0755 (rwxr-xr-x) to 0744 (rwxr--r--)
mode of `./codis.sh' changed from 0644 (rw-r--r--) to 0744 (rwxr--r--)
mode of `./ne fil.sw' changed from 0644 (rw-r--r--) to 0744 (rwxr--r--)
mode of `./.whois1.sh.swo' changed from 0644 (rw-r--r--) to 0744 (rwxr--r--)
mode of `./new file' changed from 0644 (rw-r--r--) to 0744 (rwxr--r--)
mode of `./ezik.sh' changed from 0644 (rw-r--r--) to 0744 (rwxr--r--)
mode of `./.whois1.sh.swp' changed from 0600 (rw-------) to 0744 (rwxr--r--)
mode of `./whois1.sh' retained as 0744 (rwxr--r--)

I now know that the correct usage for the  find part was
find .  -iname '*.sh' -print0
So I created another find like so:
find . \! -iname '*.sh'  -print0 | xargs -0 chmod 600
so that I may set back the permissions for non-sh files (yes, I see that some files have 644 perms, not 600 but it does not matter now). The output for this command is :
chmod: cannot access `./ne fil.sw': Permission denied
chmod: cannot access `./.whois1.sh.swo': Permission denied
chmod: cannot access `./new file': Permission denied
chmod: cannot access `./.whois1.sh.swp': Permission denied

I used sudo too but still nothing...
I see I do not understand permissons properly... If I understand correctly I need x permisions  for directory direc too in order to execute commands in said directory.

A: Your find cmd also finds the current directory ".". The rights of this directory will then be set to 600 and therefore you'll lose the rights to touch the files within this directory.
So cd .., chmod 700 said directory and then run your reverting find, which now excludes the current directory, like this:
find . \! -path . \! -iname '*.sh' -print0 | xargs -0 chmod 600


text:
Q: Typescript не проверяет лишние свойства при передачи объекта по ссылке  type Options = {
  baseURL: string
  cacheSize?: number
  tier?: 'prod' | 'dev'
 }

 class API {
  constructor(private options: Options) {}
 }

 // Ожидаемо верно
 new API({
  baseURL: 'https://api.mysite.com',
  tier: 'prod'
 })

 // Ожидаемо неверно
 new API({
  baseURL: 'https://api.mysite.com',
  badTier: 'prod'
 })

Почему нет ошибки в следующем фрагменте кода:
 let badOptions = {
  baseURL: 'https://api.mysite.com',
  badTier: 'prod'
 }

 new API(badOptions)


text:
Q: How to extract images from a webpage as Facebook does? If I insert in my wall a link like this:
http://blog.bonsai.tv/news/il-nuovo-vezzo-della-lega-nord-favorire-i-lombardi-alluniversita/
then facebook extract the image in the post and not the first image in the webpage ( not image logo or other little images for example ) !!
How facebook does that ?

A: Hm, impossible to say without more information about the algorithm they use.
However, from looking at the page's source code you can see that while the image of Bossi is not the first image in the page, it's the first inside the divs "page_content" and "post_content". Maybe Facebooks knows the HTML IDs that the blogging system (Wordpress in this case) uses, and uses these to find the first image that is actually part of the page content.
That would actually be a good idea, and is essentially an implementation of the "semantic web"...

A: As others have said, we have no idea how Facebook decides what to choose in the absence of any relevant metadata (though Sleske's guesses seem reasonable; I'd also guess that they look at the first big image), but you can avoid that by going the correct route and simply giving facebook (and similar services) addiotnal metadata about your page by using Open Graph Protocol tags, for example if you want to specify a particular image to use for a facebook like, you'd include this in your head tag:
<meta property="og:image" content="<your image URL>" />

OGP is also used by LinkedIn, Google+ and many others.
If you're in Wordpress you can control these tags with an open graph plugin. Other systems can do it manually or via their own plugins.

A: I can imagine that the Facebook crawler can identify the actual content part, and select an image from it. Similar functionality is used by the Safari Reader functionality. It probably helps that the software used is Wordpress, which is the most popular blogging software. It's a quick win for Facebook to add specific support for this software.

A: My guess is facebook has built some algorithms for distinguishing the actual content from the other data in a html page. When looking at the page you provided it's quite easy since the html element that contains the page content has id="page_content" which is self-explanatory.


text:
Q: How to fix heading at left of buttons I am developing an page but i am not really good in web designing.
my html is
<!DOCTYPE html>

<link href="https://googledrive.com/host/0B0vEuOxa0lxIajBoRU1UWmdOQjQ/style.css" rel="stylesheet" type="text/css" />
<link href='http://imageshack.us/a/img41/663/iconbg.gif' rel='icon' type='image/gif'/>

<title>Pointer Calculator...</title>

Home
 Admin Login

My Heading

I was trying to set heading at top and left of the buttons can you please help me,Any other recommendations is highly appreceated.

A: You have used css from google drive for h1 rule where font-size for h1 is 55px which is too much .However I have post this html and css code may be useful for you .

<!DOCTYPE html>

<link href="https://googledrive.com/host/0B0vEuOxa0lxIajBoRU1UWmdOQjQ/style.css" rel="stylesheet" type="text/css" />
<link href='http://imageshack.us/a/img41/663/iconbg.gif' rel='icon' type='image/gif'/>

<title>Pointer Calculator...</title>

My Heading

        Home
         Admin Login

A: Try this
HTML code
<!DOCTYPE html>

<link href="https://googledrive.com/host/0B0vEuOxa0lxIajBoRU1UWmdOQjQ/style.css" rel="stylesheet" type="text/css" />
<link href='http://imageshack.us/a/img41/663/iconbg.gif' rel='icon' type='image/gif'/>

<title>Pointer Calculator...</title>

Home
 Admin Login

My Heading

A:

        My Heading
        Home
         Admin Login

JsFiddle Here http://jsfiddle.net/rn5u5/

A: Just change the previous style code with the new style code!

A: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>::W3 Origin::</title>
<link href="stylesheet.css" rel="stylesheet" type="text/css" />

<link href="SpryAssets/SpryTabbedPanels.css" rel="stylesheet" type="text/css" />

<link href="css/dropdown/dropdown.css" media="screen" rel="stylesheet" type="text/css" />
<link href="css/dropdown/themes/nvidia.com/default.advanced.css" media="screen" rel="stylesheet" type="text/css" />

 +
 www.

Home

About us

seo services

SMO

LINK BUILDING SERVICES

PPC SERVICES

SEO CONTENT WRITING

NETWORK

TWITTER

FACEBOOK

LINKEDIN

PACKAGES

nZone

SLI Zone

CUDA Zone

Developer Zone

PartnerForce

Gelato Zone

WHY US

REQUEST A QUOTE

CONTACT US

A: body{
font-family:'Georgia', Arial, Verdana;
font-size:12px;
color:#4b4a48;
line-height:18px;
text-decoration:none;
background-color:#f5f5f5;
margin:0px;
padding:0px;}

#wrapper{
width:1000px;
height:auto;
overflow:auto;
text-align:left;
background-color:#FFFFFF;}

#header{
width:auto;
height:147px;
border-bottom:1px solid #FFFFFF;
background-color:#142a38;}

#header_left{
float:left;
width:480px;
padding:15px 0px 0px 0px;}

#logo{
float:left;
padding:30px 70px 0px 40px;}

#header_right{
float:right;
width:500px;}

#header_bar{
width:auto;
height:20px;
padding:5px 15px 5px 5px;
text-align:right;
background-image:url(images/bg-top-right.gif);
background-repeat:repeat-y;}
#header_bar img{
margin:5px 5px 0px 50px;}

#follow_us{
text-align:right;
padding:30px 30px 0px 0px;}
#follow_us img{
margin:0px 5px 0px 5px;}

#flash_header{
clear:both;}

#content{
width:auto;
height:auto;
overflow:auto;
clear:both;
margin:0px 0px 10px;
padding:20px 15px 25px 15px;}

.float_wrapper{
width:auto;
height:auto;
overflow:auto;
clear:both;}

#left_part{
float:left;
width:690px;
height:auto;
overflow:auto;
line-height:19px;}

#left_part ul{
margin:0px;
padding:0px;}

#left_part li{
list-style-type:none;
padding:0px;
margin:0px 0px 0px 5px;}

#right_part{
float:right;
width:265px;
height:auto;
overflow:auto;}

#tab_panel{
clear:both;
height:240px;
overflow:visible;
border:1px solid #25729e;
background-color:#f9f9f9;
margin-bottom:10px;}

.panel_left_img{
float:left;
padding:0px 35px 0px 0px;}

.panel_right_img{
float:right;
padding:0px 0px 0px 0px;}

#enquiry_panel{
height:240px;
border:1px solid #24709c;
background-color:#e7f2fa;
margin-bottom:10px;}
.panel_content{
padding:10px;}
.panel_content label{
font-size:14px;
color:#4c4c4c;
line-height:20px;
text-decoration:none;
float:left;
width:70px;
margin-bottom:5px;}
.panel_content input{
font-size:13px;
color:#525252;
line-height:18px;
float:right;
width:165px;
height:18px;
border:1px solid #7f7f7f;
background-color:#fef5cb;
margin-bottom:5px;}

.panel_content textarea{
font-size:13px;
color:#525252;
line-height:18px;
float:right;
width:160px;
height:60px;
border:1px solid #7f7f7f;
background-color:#fef5cb;}
.line{
clear:both;
padding-bottom:5px;
}

.seprator{
clear:both;
height:10px;}

.min_seprator{
clear:both;}

.sections_left{
float:left;
width:47%;
height:auto;
overflow:auto;
border:1px solid #24709c;
padding:8px;}
.sections_left img{
border:1px solid #d6d7d8;}

.sections_right{
float:right;
width:47%;
height:auto;
overflow:auto;
border:1px solid #24709c;
padding:8px;}
.sections_right img{
border:1px solid #d6d7d8;}

#footer{
width:auto;
height:138px;
overflow:visible;
clear:both;
background-image:url(images/bg-footer.gif);
background-repeat:repeat-x;
padding:15px 10px 10px 10px;}
#sitemap_links ul{
height:100px;
margin:0px;
padding:0px;}
#sitemap_links li{
width:130px;
font-size:13px;
color:#ffffff;
text-decoration:none;
float:left;
list-style-type:none;
border-right:1px dotted #ddd8cb;
text-align:left;
padding:0px 0px 0px 20px;
margin:0px 0px 0px 0px;}
#sitemap_links li a{
color:#ffffff;
text-decoration:none;}
#sitemap_links li a:hover{
color:#ffd171;
text-decoration:none;}
#sitemap_links li.end{
color:#ffffff;
text-decoration:none;
border-right:none;}

#sitemap_links li ul{
margin:0px;
padding:0px;}
#sitemap_links li li{
font-size:13px;
color:#fef1dd;
text-decoration:none;
list-style-type:none;
text-align:left;
border-right:none;
padding:0px 0px 0px 0px;}
#sitemap_links li li a{
color:#fef1dd;
text-decoration:none;}
#sitemap_links li li a:hover{
color:#fef1dd;
text-decoration:underline;}

#footer_strip{
width:auto;
height:30px;
overflow:auto;
clear:both;
padding:5px 15px 5px 15px;
font-size:11px;
color:#ffffff;
line-height:18px;
text-decoration:none;
background-color:#1a425c;}
#footer_nav{
font-size:11px;
color:#ffffff;
line-height:18px;
text-align:right;
text-decoration:none;}
#footer_nav a{
color:#ffffff;
text-decoration:none;}
#footer_nav a:hover{
color:#ffffff;
text-decoration:underline;}

h1{
font-size:17px;
color:#ffffff;
line-height:18px;
text-decoration:none;
font-weight:normal;
text-align:center;
padding:5px;
background-color:#142a38;
margin:0px;}

h2{
font-size:16px;
color:#142a38;
line-height:18px;
text-decoration:none;
font-weight:normal;
text-align:left;
padding:8px 5px 8px 0px;
margin:0px;}

h3{
font-size:14px;
color:#142a38;
line-height:18px;
text-decoration:none;
font-weight:normal;
text-align:left;
padding:0px 0px 0px 0px;
margin:0px;}

.blue-txt{
font-size:13px;
font-weight:bold;
margin:0px;
padding:0px;
color:#3c6078;
padding-bottom:5px;
border-bottom:1px dashed #142a38;}

.blue-txt a{
color:#3c6078;
text-decoration:underline;}

.blue-txt a{
color:#3c6078;
text-decoration:underline;}

.org-txt{
font-size:11px;
font-weight:bold;
margin:0px;
padding:0px;
color:#c74c01;
line-height:22px;}

.org-txt ul{
margin:0px;
padding:0px;}

.org-txt li{
list-style-type:circle;
padding-left:10px;}

.org-txt li a{
color:#c74c01;
text-decoration:underline;}

.org-txt li a:hover{
color:#c74c01;
text-decoration:none;}

.org-txt li ul{
margin:0px;
padding:0px;}

.org-txt li li{
font-size:12px;
color:#4b4a48;
font-weight:normal;
margin-left:40px;
list-style-type:circle;
line-height:19px;
text-decoration:none;}

.org-txt li li a{
color:#4b4a48;
text-decoration:none;}

.org-txt li li a:hover{
color:#4b4a48;
text-decoration:underline;}

p{
font-size:12px;
color:#4b4a48;
line-height:18px;
text-decoration:none;
text-align:justify;
padding:5px 0px 8px 0px;
margin:0px;}

.list_txt ul{
margin:0px 0px 0px 0px;
padding:0px 0px 0px 20px;}
.list_txt li{
font-size:12px;
color:#4b4a48;
text-decoration:none;
list-style-position:inside;
list-style-image:url(images/list-arrow.gif);}
.list_txt  li a{
color:#4b4a48;
text-decoration:none;}
.list_txt li a:hover{
color:#a80001;
text-decoration:underline;}

.white_txt{
font-size:12px;
color:#ffffff;
line-height:18px;
text-decoration:none;}
.white_txt a{
color:#ffffff;
text-decoration:none;}
.white_txt a:hover{
color:#ffffff;
text-decoration:underline;}

.red_txt{
font-size:12px;
color:#913700;
line-height:25px;
text-align:right;
text-decoration:none;}
.red_txt a{
color:#913700;
text-decoration:underline;}
.red_txt a:hover{
color:#913700;
text-decoration:none;}

.img_right{
float:right;}

.right_panels{
clear:both;
margin-bottom:8px;
border:1px solid #24709c;
background-color:#f5f5f5;}
.panel_content{
padding:8px 8px 5px 8px;}


text:
Q: "I broke my arm" vs "my arm was broken"
I broke my arm.

In my language (Persian), if I say this to one of my friends, her response would be like this: "Are you out of your mind? Why did you break your arm?" because it implies that I broke my arm on purpose. And we usually say this in passive voice.
So I actually think passive is more correct. I mean, you fell down and your arm was broken. You didn't want to break your arm. So I don't get why we say this in the active voice.

A: It is a bit odd to say it like this, but it's simply accepted idiom.
To add to the other answers, if we felt no agency at all in the act, we might say, "My arm was broken in a car crash" or "I had my arm broken in a fight".
There are some diseases which cause bones to fracture essentially spontaneously. For those cases, or where you really wanted to be neutral about an event, you could say "I've had a broken arm".
It's grammatical to say "my arm broke" but a bit uncommon in isolation. It would make sense to say "my arm broke in a fall" or "I fell, my arm broke, by ankle twisted, and my head hit the pavement". It does come across a bit like you're dissociating from it.
If you did want to convey a higher degree of fault, you could say "I broke my own arm". For example, "I hit the wall to make a hole in it, but I just broke my own arm".

A:
I don't get why we say this in an active voice.

English is not Persian. There is no sense of "on purpose" when saying "I broke my arm". It refers to the cause of the breakage, not the reasons.

*

*I broke my arm →  My actions caused my arm to be broken.

*A criminal broke my arm → A criminal's actions caused my arm to be broken.

There is nothing intrinsically in the above that says either action is deliberate. People might assume that the criminal did it on purpose but that is not necessarily true.
Examples

*

*I needed money so I broke my arm to get an insurance pay-out. (deliberate)

*I broke my arm when I slipped on some ice.  (accidental)

*A criminal broke my arm by hitting it with an iron bar. (deliberate)

*A criminal broke my arm by accidentally knocking me over when running from the police. (accidental)

A: Also, would be useful among those examples to actually add the intentional breaking of one's own arm: "I broke my arm on purpose/purposefully", beyond the case of cause "and so" which become conditional. Also, just like any language, physical presence whilst delivering the spoken work can be accompained by expression and body language, such that further innotation on the 'I' or 'broke' (depending), can make it declarative. "I broke my arm/I broke my arm", will be sufficient to imply the [on purpose/purposefully], with said expressions.

A: Either is correct but the active voice carries some element of responsibility for the action, without declaring intent.
I broke my arm for the insurance money (per another answer) ... active, with intent, quite rare, and "Are you crazy?" is a perfectly appropriate answer.
I was cycling too fast and hit a patch of ice, when the bike went down I broke my arm. Active; no intent, but I have some responsibility because I could have slowed down in poor conditions.
A car knocked me off my bike, and my arm was broken. Passive is probably the most appropriate here, though active would be acceptable.
Passive can be used for comic effect...
There was so much beer at the party last night. Mistakes were made...
(I don't want to admit to taking any part in what happened!)

A: I broke my arm would be preferred because it's in active voice.  My arm was broken is in passive voice.  Passive voice is generally avoided in English because the subject of the sentence is not performing the action of the verb, which makes the sentence harder to understand in English.
In the I broke my arm it's the I (you) acting on your arm.  In the 2nd My arm was broken your arm didn't do the breaking - who did?  That's why the 2nd sentence is in passive voice - it leaves out who is doing the action.
We know you didn't mean to break your arm on purpose.  It's the same as saying I fell on the ice.  You didn't mean to fall, it just happened.  You can be acted on by things you don't want to be.
Take a look at the grammarly page about passive voice.

A: "I broke my arm." is correct in the example you gave. It does not mean you wanted to break your arm, just like you can say, "I tripped" without meaning you did it on purpose.
"My arm was broken." is not correct in your example. Passive voice means there was another party involved. Leaving out the actor(s) means the actor(s) are unknown or unimportant.
Passive voice also usually means that the subject was a victim of some sort. If you add in the actor you'll get see better why this would be wrong. "My arm was broken by me."


text:
Q: Return True if Array Contains a Specific String - JSONata Is there a way in JSONata to have a function return TRUE if it finds a specific string within a provided array? For example I have an array of colors:
const myArray =  [red,blue,green,pink]
I am trying to figure out an expression that would search that array for "blue" and return true if it finds the value.
On the JSONata documentation, I found a function called $boolean(arg)that I think I would need to use but I'm not sure how to implement it. The documentation shows an argument type option as "array: contains a member that casts to true", but I can't really tell how to implement it.
Would it be as simple as $boolean(myArray, "blue")?

A: The in operator is what you need. See https://docs.jsonata.org/comparison-operators#in-inclusion
In your case, the expression "blue" in myArray will return true.  See https://try.jsonata.org/r0q7GnSOh

A: edit: Thought this was python, but maybe you could use something similar for JSONata
you can make a for loop with an if condition to check your condition
listOfStrings = ['red','green','blue']

for strings in listOfStrings:
    if listOfStrings[strings] == 'blue':
        return True


text:
Q: keytool error: java.lang.Exception: Certificate not imported, alias mykey already exists I am trying to install a client certificate in my JVM to call a https soap service, but when running the
keytool -import command I get the below error:
**
keytool error: java.lang.Exception: Certificate not imported, alias  already exists
**
Here is the command I am using, please note I am using Java11
**
C:\Softwares\java-11-openjdk-11.0.7.10-1.windows.redhat.x86_64\lib\security>keytool -import -keystore cacerts -file "C:\Softwares\client.certificate.pfx"
**
Please suggest.

A: Every entry in the java keystore is identified by a key called alias. It has to be unique for a given keystore. If you don't provide one, the default value the keytool uses is mykey. Looks like there is an entry with mykey already in your keystore. All you have to do is give a name yourself. You can do this using the alias attribute, like this:

keytool -import -keystore cacerts -file "C:\Softwares\client.certificate.pfx" -alias third_party_ca

You can use any name as long as it is unique.


text:
Q: Jquery Mobile document.ready not being called from view I am not able to get document.ready event or attach button click event.
What am i missing here?
This is how my view looks like:
@section script
{

}
<input type="text" id="txtStop" />
<input type="button" id="btnGo" value="Get Schedule" />

This is how my layout file looks like:

    <link href="../../Content/themes/base/jquery.mobile-1.0b3.css" rel="stylesheet" type="text/css" />

@RenderSection("script")

@RenderBody()

Page Footer

A: You're not declaring the document.ready properly
Currently it's
 $(document.ready(function(){
It either needs to be
$(function(){
    alert('Document is ready!');
     $('#btnGo').bind('click', function () {
        alert('User clicked button');
    });
});

or
$(document).ready(function(){ .... });

A: You have errors in your script (incorrect bracing and parens).  Change it to this:

There would have been javascript errors showing in the error console to show you this problem.

A: Actually, you don't even need the document ready event.  Just place the bind event somewhere after the button exists on the page.  This is universal, regardless of your use of jquery mobile or not, you can bind an event handler to an object as soon as it exists within the DOM. Depending on how much you're loading on the page and how long it takes, it might be a higher performance way of doing things.

    ...

    ...

    ...
    click me
    ...


text:
Q: C# assure that the binFile in zip file is really updated This question is a follow up question of
Read binary file from a zip file from C# without unzipping it
After read the bin file from the zip file, I read it and make some changes to the data (id1, id2, value1) and then write to a new memorystream.
Then, in C#, I remove the zipentry from the zip file and add the new memorystream as a zip entry with the same name.
 // read data and made changes, then write to a MemoryStream called myms
 MemoryStream myms = new MemoryStream();
 // then
 ZipFile.RemoveEntry(binFileName); // remove the file with non-normalized rm factors
 ZipFile.AddEntry("subFolder/" + binFileName, myms.ToArray());

After all is done, I manually unzipped the zip file and found that the date and time of the binFile is still the time when it was created one week ago not the new time where it was replaced.
How to make sure that the new data has been written to the binFile ?


text:
Q: Adding multiple new shipping methods I'm following the guide located at http://inchoo.net/magento/custom-shipping-method-in-magento/
but I'm unsure if this allows me to add multiple shipping methods. I could install the module multiple times but I'm not sure this is the best way if the class supports multiple shipping methods.
The question here is, does the above tutorial allow me to add multiple shipping methods under 1 module?

A: You can create multiple shipping methods into one module, for example the fedex module will display all the available shipping type (Overnight, 2 Business Days ...)
$result = Mage::getModel('shipping/rate_result');

....

$rate = Mage::getModel('shipping/rate_result_method');
$rate->setCarrier($this->_code);
$rate->setCarrierTitle($this->getConfigData('title'));
$rate->setMethod('large');
$rate->setMethodTitle('Overnight');
$rate->setPrice(5);
$rate->setCost(0);
// append first shipping type
$result->append($rate);

$rate = Mage::getModel('shipping/rate_result_method');
$rate->setCarrier($this->_code);
$rate->setCarrierTitle($this->getConfigData('title'));
$rate->setMethod('large');
$rate->setMethodTitle('2 Business Days');
$rate->setPrice(10);
$rate->setCost(0);
// append second shipping type
$result->append($rate);

....


text:
Q: How can I align these divs with inline-block? I have two divs with text, but one should be aligned to the top left, and the other should be centered, but not on the same line as the first.
Like this:
----------------------------------------------
|Backstage
|Issue 4
|
|                 New Fish Species
|              Migrating To The Town
|

This is my current code:

BACKSTAGE

Issue 4, June 16, 2003

New Fish Species

Migrating To The Town

How can I fix this?

A: You don't need to do set the divs to inline-block. You really dont have to do anything more than text-align: center on the second div

BACKSTAGE

Issue 4, June 16, 2003

New Fish Species

Migrating To The Town

FIDDLE

A:

BACKSTAGE

Issue 4, June 16, 2003

New Fish Species

Migrating To The Town

This should get you on the right track; with a few adjustments. Look at some of the differences and that should help.


text:
Q: Get number of jira users How can I get the number of JIRA users? And how can I get the user number JIRA is licenced for?
I'll appreciate if you provide examples using different layers e.g. Using database query, or JIRA API call, or a method to call in JIRA plugin.
// JIRA instance is using Crowd

A: This is how to get users from group jira-users. Only this user group affects license user count.
ComponentAccessor.getGroupManager().getUserNamesInGroup("jira-users").size();

You could also inject groupManager in your plugin.
I don't know how to get user number JIRA is licenced for. I think it's not stored in your instance data or DB.

A: have a look at https://confluence.atlassian.com/jirakb/get-list-of-licensed-users-in-jira-server-278695452.html
But to have the exact licence count, the SQL query must be improved by adding this clause << AND group_id = 'jira-users' >>
So the query is :
SELECT DISTINCT u.lower_user_name
FROM   cwd_user u
       JOIN cwd_membership m
         ON u.id = m.child_id
            AND u.directory_id = m.directory_id
       JOIN licenserolesgroup lrg
         ON Lower(m.parent_name) = Lower(lrg.group_id)
       JOIN cwd_directory d
         ON m.directory_id = d.id
WHERE  d.active = '1'
       AND u.active = '1'
    AND license_role_name = 'jira-software'
    AND group_id = 'jira-users'; // <- improvement


text:
Q: How can I pass command-line arguments when creating a new Database connection in SQLPro? When I start my MySQL client from the command-line, I do the following:
$ mysql -u root -p -h 127.0.0.1 --init-command="SET SESSION wait_timeout=300"

I set the session wait_timeout to 300 seconds for security purposes. If there is no database activity for 5 minutes, I want the connection to be killed so that it is not actively left open for long periods of time which is a security risk.
However, I really prefer using the Mac desktop application SequelPro to access the database instead of the command-line shell. It's my bread-and-butter. I absolutely love it. Here's what it looks like when I open a DB connection in SequelPro:

So how can I give SequelPro the same `--init-common argument I gave on the command-line above? Or is there any other way for me to achieve the security goal I'm trying for?

A: If you want to make this global setting for everyone connecting from any tool. You add this to the configuration file, my.cnf (if you're running MySQL on Unix-based OSs) or my.ini (if you're running MySQL on Windows-based OSs).
This is from MySQL documentation about wait_timeout

The number of seconds the server waits for activity on a
  noninteractive connection before closing it.
On thread startup, the session wait_timeout value is initialized from
  the global wait_timeout value or from the global interactive_timeout
  value, depending on the type of client (as defined by the
  CLIENT_INTERACTIVE connect option to mysql_real_connect()). See also
  interactive_timeout.

So, set this global parameter in [mysqld] section of your configuration file to keep your security in check.
[mysqld]
interactive_timeout=300
wait_timeout=300


text:
Q: Limit on Runnable creation in java I have a system which continuously receives messages. I need to pass these messages to a new system. But there will be millions of messages I will be sending here. I want to run this on a separate thread. In that case can we create millions of runnables to post the task on ScheduledThreadPoolExecutor?

A: I think there is no need to create millions of Runnable instances. I don't know other details of your system but it looks that you can send received message to a new system straight away after receiving.
If you wish to add some resistancy then you should consider using a message queue or a database to store received messages. That way you will guard them against being lost in case of a crash/process exit. And a separate thread pool should be processing messages from this storage (queue or database) by sending to a new system.


text:
Q: Likelihood test ratio for random sample with p.d.f. $f(x\mid \theta) = e^{-(x-\theta)}$ I don't know how to find the max region of the denominator since doing the usual gives me a constant as the derivate of the likelihood function of theta.
The problem is as follows
Let $X_1 , \ldots , X_n$ be a random sample with
$$f(x\mid \theta) = e^{-(x-\theta)}$$
where $x \in [\theta,\infty)$
find $\lambda(x)$ where $H_0: \theta = \theta_0$ and $H_1: \theta > \theta_0$
so I know that the numerator since it's just a point, is equal to the maximum likelihood function on $\theta_0$
but if I try to maximize the denominator since the Likelihood function is
$$ \prod^n_{i=1} e^{-(x_i-\theta)} = e^{n\theta-n \bar{x} } $$
but I can't maximize the likelihood from its derivative in the region $[\theta_0 , \infty]$

A: The main error you did is that the likelihood you stated is WRONG. You did not take into consideration that the suppport is depending on the parameter.
Let's see how to proceed in this case:
$$f(x|\theta)=e^{\theta}e^{-x}$$
$x\geq\theta$
$\theta \in \mathbb{R}$
This implies that $min(\mathbf{X})=X_{(1)}\geq\theta$

The likelihood is the following
$$L(\theta)=e^{n \theta}e^{-\Sigma_i X_i}\cdot\mathbb{1}_{[\theta;\infty)}(x_{(1)})$$

Now if we take two points $\theta'<\theta''$ we get the following likelihood ratio
$$\frac{L(\theta';\mathbf{x})}{L(\theta'';\mathbf{x})}=\frac{e^{n\theta'}\mathbb{1}_{[\theta';\infty)}(x_{(1)})}{e^{n\theta''}\mathbb{1}_{[\theta'';\infty)}(x_{(1)})}=\begin{cases}
+\infty,  & \text{if $x_{(1)}<\theta''$ } \\
e^{n(\theta'-\theta'')}, & \text{if $x_{(1)}\geq\theta''$ }
\end{cases}$$
Thus in this case we have a "Monotone Likelihood Ratio" that is a "Non increasing LR" with respect to the Statistic $T=X_{(1)}$ and so we can apply the following theorem

A: For any real $\theta$, the likelihood function given the sample $\boldsymbol x=(x_1,\ldots,x_n)$ is
\begin{align}
L(\theta\mid \boldsymbol x)&= \begin{cases}e^{-n(\bar x -\theta)}&, \text{ if }x_1,\ldots,x_n\ge \theta \\ 0 &, \text{ otherwise }\end{cases}
\\&=\begin{cases}e^{-n(\bar x -\theta)}&, \text{ if }x_{(1)}\ge \theta \\ 0 &, \text{ otherwise }\end{cases}\,,
\end{align}
where $x_{(1)}=\min\{x_1,\ldots,x_n\}$.
This is a non-decreasing function of $\theta$, so its maximum is reached for the maximum possible value of $\theta$, namely $\theta=x_{(1)}$.
Now suppose $\theta$ is restricted to $[\theta_0,\infty)$. If $x_{(1)}\ge \theta_0$, then $L(\theta\mid \boldsymbol x)$ is still maximized at $\theta=x_{(1)}$. But if $x_{(1)}<\theta_0$, then because of the nature of the likelihood, $L(\theta\mid \boldsymbol x)$  is maximized at the boundary point $\theta=\theta_0$. A sketch of the likelihood function makes this point clear.
So the restricted MLE of $\theta$ in this case is  $$\hat\theta=\begin{cases}x_{(1)}&,\text{ if }x_{(1)}\ge \theta_0 \\ \theta_0 &,\text { if }x_{(1)}< \theta_0\end{cases}$$
The likelihood ratio test criterion is therefore $$\Lambda(\boldsymbol x)=\frac{\sup_{\theta=\theta_0}L(\theta\mid \boldsymbol x)}{\sup_{\theta\ge \theta_0}L(\theta\mid \boldsymbol x)}=\frac{L(\theta_0\mid \boldsymbol x)}{L(\hat\theta\mid \boldsymbol x)}$$
Simplify this and reject $H_0$ for small values of $\Lambda$ to obtain the likelihood ratio test. This test would coincide with the uniformly most powerful test derived here for the same problem.


text:
Q: AngularJS ngResource not working I have the following problem:
I am using ui-router to display a ng-grid on a page. But the $resource is not changing the parameter from the url when sending to server (e.g. http://bcunix.test:8080/MYAPP/eq/:Id). The :Id is not changed, and I get Bad request from the server because I am sending :Id.
index.js
(function() {
'use strict';
var brgEquipments = angular.module('brg.equipments',
        [
            'ui.router',
            'brg.equipments.controllers'
        ]);
brgEquipments.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/equipments/list');

    $stateProvider.state('list', {
        url: '/equipments/list',
        templateUrl: '/scripts/modules/equipments/views/grid_list.html',
        controller: 'equipmentsListCtrl',
        resolve: {
            // A string value resolves to a service
            eqService: 'eqService',
            // A function value resolves to the return
            // value of the function
            equipments: function(eqService) {
                return eqService.query().$promise;
            }
        }
    });

});

})();
service.js
(function() {
'use strict';
var eqCtrls = angular.module('brg.equipments.controllers');

eqCtrls.factory('eqService', ['$resource', function($resource) {
        return $resource("http://bcunix.test:8080/MYAPP/eq/:Id",
                { Id: "@Id"},
        {
            update: {
                method: "PUT"
            },
            remove: {
                method: "DELETE"
            }
        });
    }]);

})();
Result:
GET http://bcunix.test:8080/MYAPP/eq/:Id 400 (Bad Request)
Any help / hints would be appreciated.
Thanks,
AdiP

A: Lol,
So finally I figured it out.
Looks like bower install ngResource is not equal to bower install angular-resource.
I was using the wrong version of ngResource.
Updated to latest version and now it's working.
Thanks ThomasP1988 for your interest in solving my problem.
Best regards,
AdiP


text:
Q: SLF4J: Use XLogger with LocLogger We are currently using CAL10N to localize log messages generated by SLF4J. To do this, we need to use the LocLogger class to define a logger for every class.
Few weeks into development, there comes a time where you have a few bug reports with logs attached - they do have nicely logged stack traces (thanks to SLF4J) for exceptions being thrown, but turns out we have a hard time figuring out the flow since since everyone's new to the code and the flow of things keeps changing every other day!
What we need is ENTRY/EXIT logs for every method. I was hoping that SLF4J will provide a way to do that in the least painful and fastest possible way: and ho behold! It certainly does!
The XLogger class provides methods that aid in such verbose logging (see this link), but after looking at the API docs, looks like both LocLogger and XLogger implement the Logger interface.
So the question is (we got to it finally!) - is it possible to use the LocLogger with all the localization benefits of CAL10N in peaceful harmony with XLogger, that provides all the verbose logging goodies?

A: No real answer for this yet - worked around it by leveraging a feature of the underlying implementation.
We're using log4j as the implementation under slf4j. The PatternLayout supports printing the package name+method name of the origination of the log message with these specifiers: %C.%M
So we simply log well-defined strings, +++ as the first line in every method and --- just before returning, to a logger for that class.
Solves the purpose, but not a solution to the original question.