text:
Q: How can we use proxy for connecting to dns server on requests? Requests doesn't resolve nameservers via proxies argument given to it by default.
How can we use make it do that ?

A: Bases on requests documentation:

Using the scheme socks5 causes the DNS resolution to happen on the client, rather than on the proxy server. This is in line with curl, which uses the scheme to decide whether to do the DNS resolution on the client or proxy. If you want to resolve the domains on the proxy server, use socks5h as the scheme.

Hence we have to just set socks5h for the scheme of the proxy given to the proxies argument.


text:
Q: Convert JsonArray to JsonObject I have this JSON array:
[{
   "MOTIVO": "ok",
   "ESTATUS": "10",
   "TIPO": "1",
   "ACCMOTIDN": "2",
   "AVMVOR1IDN": "31089",
   "AVMVORIDN": "23163",
   "SPCHRZIDN": "75"
}, {
     "MOTIVO": "ok",
     "ESTATUS": "10",
     "TIPO": "1",
     "ACCMOTIDN": "2",
     "AVMVOR1IDN": "31090",
     "AVMVORIDN": "23163",
     "SPCHRZIDN": "75"
}]

I validate with JSONLint and it is a valid JSON. How can I convert into a jsonObjects? This is what I have at this moment:
public ArrayList<Object[]>Auth_Rej_Order(String obj_auth,mPedidoDet
mpedidodet)
 {
     try
     {
         res_array=new ArrayList();
         obj_auth_json=new JSONArray(obj_auth);
         obj_auth_list=new ArrayList<>();
         obj_auth_list_map=new HashMap<>();
         JSONObject obj_json;
         for(int i= obj_auth_json.length()-1;i>=0;i--)
         {
             obj_json=new JSONObject(obj_auth_json);
             Iterator<?> keys = obj_json.keys();
             while( keys.hasNext() )
             {
                String key = keys.next().toString();
                obj_auth_list_map.put(key,obj_json.get(key));
             }
             obj_auth_list.add(obj_auth_list_map);
         }

     }
     catch(Exception ex)
     {
         //Error inesperado.
        res_array.clear();
        res_obj_array=new Object[1];
        res_obj_array[0]="001";
        res_array.add(res_obj_array);
     }

     return res_array;
 }

I'm trying with:
obj_json=new JSONObject(obj_auth_json)
obj_json=new JSONObject(obj_auth_json.get(position))
obj_json=new JSONObject(obj_auth_json.getJSONObject(position))
obj_json=new JSONObject(obj_auth_json.getJSONArray(position));

and any of them worked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails has one associaton. Prevent overwrite if the child already exists Is there a rails option to prevent a Parent with an has one association from overwriting the child object if it already exists?

A: You can add a custom validation:
class Parent

  validate on: :update do
    unless child_id_was == nil
      errors.add(:child, "cannot be overwritten") if child_id_changed?
    end
  end

end


text:
Q: 'Character Array' of integers to 'Integer array' My Requirement :
Taking some (unknown number) of integers as input from user and store them in a numeric array.
Eg: input:  25 3 4 78. I want them to be stored in a numeric array, say num as
    num[0] = 25
    num[1] = 3
    num[2] = 4
    num[3] = 78
    . . .

What I did :

*

*Stored the input in a character array.
gets(arr);
 //takes input from command prompt and stores in a string

*Then I'm trying to find spaces and separate the characters, but it turns out that a double digit number(say,25) is stored as 2 and 5 but not as 25.
How do I achieve this?

A: Well, as you did not show your code, I'll also not provide any code, but I'll be more than happy to provide you with the flow-chart.

*

*Define one array large enough (maybe change to dynamic allocation later).

*Take the input from user (not command line arguments) using fgets().

*use strtok() to tokenize the input using space  as delimiter.

*If a non-NULL token is received, use strtol() to convert the token to int or long.

*If strtok() returned NULL means you've got all the tokens and the input is empty, finish up, you got your int array.


text:
Q: How to use map()? I have a function mostraReferti where i get a list of items from the database and store them in the state into referti[]. I need to display those items in a dropdown. I first tried to write  {this.state.referti} in <option> but what i got was only the first item of the table. I need to use map(). So i tried this code:
class CredentialsPanel extends Component {
  constructor(props) {
    super(props)
    this.state = {
      referti: []
     }
     this.handleInputChange = this.handleInputChange.bind(this);
     this.mostraReferti = this.mostraReferti.bind(this);
   }

   static getDerivedStateFromProps(nextProps) {
     const { account } = nextProps
     return { id: account.id }
  }

   handleInputChange(event) {
     const target = event.target;
     const value =
       target.type === 'checkbox'
         ? target.checked
         : target.value;
     const name = target.name;
  console.log("stato", this.state)
     this.setState({
       [name]: value,
     });
   }

   componentDidMount() {
     const { actions } = this.props

     requestAccountAccess((defaultAccount) => {
       actions.account.setDefaultAccount(defaultAccount)
       actions.contract.setContract(defaultAccount)
     })
    this.mostraReferti(this.state.id)
   }

   mostraReferti(id) {
     console.log("id", id)
     axios.get('http://localhost:8080/api/REFERTOs/' + id)
       .then(response => {
         console.log("response1" + JSON.stringify(response.data))
        this.setState({ referti: response.data }, () => {
             console.log(this.state);
           })
         return response.data
       })
     }

   onEnter = (evt) => {
     if (evt.key === 'Enter') {
       const { allowToProceed } = this.state
       if (allowToProceed) { this.proceed() }
     }
   }

    proceed = () => {
     const { actions, history } = this.props
     const { codiceReferto } = this.state
     actions.account.setCodiceReferto(codiceReferto)
     history.push('/consenso?panel=2')
   }

 render() {
     const { id, nextBtnDisabled } = this.state
     const refertiItems = this.state.referti.map((referti, i) => {
       return (
         <RefertiItems key={referti.hash_referto} item={referti} />
       )
     })

     return (

Compila i campi per assegnare un consenso

         <Form onSubmit={this.handleSubmit}>

            {refertiItems}

         </Form>
     )
   }
 }

And RefertiItems is:
 class RefertiItems extends Component {
    constructor(props) {
        super(props);
        this.state = {
            item: props.item
        }
    }

render(){
return (

    <select
      name="codiceReferto"
       placeholder="Selezionare Referto"
      onKeyPress={this.onEnter}     //allows you to move to the next panel with the enter key
      value={this.codiceReferto}
      onChange={this.handleInputChange}>
      <option default value="vuoto"></option>
      <option value={this.state.item.hash_referto}> .
   {this.state.item.tipo_referto}-{this.state.item.data_referto}</option>
    </select>

)
}
}

what i get is "this.state.referti.map is not a function", and the system displays a different select for every item in the table of the database.

A: You should pass directly your referti array as a prop of RefertiItems .
ReferiItems class:
class RefertiItems extends Component {
  constructor(props) {
    super(props);
    this.state = {
      item: props.item
    };
  }

  render() {
    return (

        <select
          name="codiceReferto"
          placeholder="Selezionare Referto"
          onKeyPress={this.onEnter} //allows you to move to the next panel with the enter key
          value={this.codiceReferto}
          onChange={this.handleInputChange}
        >
          <option default value="vuoto"></option>
          {
            this.props.item.map((item, key) => {
              // Use map here
              <option value={item.value} key={key}>{item.text}</option>
            })
          }
        </select>

    );
  }
}

And the render method of CredentialsPanel class looks like:
class CredentialsPanel extends Component {
  // ...
  render() {
    return (
      // ...

        <RefertiItems item={this.state.referti} />

      // ...
    );
  }
}

A: maybe this.state.referti is not a array data type, so its map is not a function, you should console.log(this.state.referti) to check its value.
If you use TypeScript, you can greatly reduce the type of such error.

A: Please Try with this, in this referti is the collection on which .map() functiona can be invoked. map() function contains 2 parameters. 1st : Item from the collection, 2nd : index. Index can be used as key to create unique elements by key.
<select>
this.state.referti.map(function(item, index){
  return <option key={index}>{item}</option>
})
</select>


text:
Q: How to apply Fourier Transform function? I want to know how I can apply "Fourier Transform function" to an image and then reconstruct the image from the phase information of the Fourier Transform?

A: Reshape the image, so that each channel has its own 2D matrix.
Normalize the image, so that its values are in the range 0 to 1.
I ~= FFTSHIFT(IFFT(FFT(I))


text:
Q: XSL Group by Country and Weight I'm making a pricing chart from an XML that contains many rates (25k+).  Each rate row specifies

*

*A service name in @service

*A country code (iso-3166) in @iso

*A weight in @kg

*The price in @pc

For each unique service I want to list

*

*Every possible weight in column headings

*List 1 row for every unique country

*The 1st cell in the row shows the name (@iso) and then the @pc for the corresponding @kg

The problem I'm having, is that all of the country names are not appearing.  Only 2 in Standard and Priority, and none in Express service.

Standard

                        FR

                        CA

Priority

                        DE

                        GB

Express

           NOTE--Should be 4 countries here

I'm hoping to output something like this

Standard

                Country

                0.1
                0.15
                0.2
                0.25
                0.3

                FR

                202
                302
                402
                502
                602

                CA

                101
                151
                201
                251
                301

Here's my XML / XSL
<xml>
 <rate service="Standard" iso="FR" kg="0.1" pc="202.0000"/>
 <rate service="Standard" iso="CA" kg="0.1" pc="101.0000" />
 <rate service="Standard" iso="CA" kg="0.15" pc="151.0000" />
 <rate service="Standard" iso="FR" kg="0.15" pc="302.0000" />
 <rate service="Standard" iso="FR" kg="0.2" pc="402.0000" />
 <rate service="Standard" iso="CA" kg="0.2" pc="201.0000" />
 <rate service="Standard" iso="CA" kg="0.25" pc="251.0000" />
 <rate service="Standard" iso="FR" kg="0.25" pc="502.0000" />
 <rate service="Standard" iso="FR" kg="0.3" pc="602.0000" />
 <rate service="Standard" iso="CA" kg="0.3" pc="301.0000" />

 <rate service="Priority" iso="CA" kg="0.5" pc="0.6000" />
 <rate service="Priority" iso="FR" kg="0.5" pc="0.6680" />
 <rate service="Priority" iso="DE" kg="0.5" pc="0.6070" />
 <rate service="Priority" iso="GB" kg="0.5" pc="0.7800" />
 <rate service="Priority" iso="GB" kg="0.75" pc="1.1050" />
 <rate service="Priority" iso="DE" kg="0.75" pc="0.8610" />
 <rate service="Priority" iso="FR" kg="0.75" pc="0.9470" />
 <rate service="Priority" iso="CA" kg="0.75" pc="0.8500" />
 <rate service="Priority" iso="CA" kg="1" pc="1.1000" />
 <rate service="Priority" iso="FR" kg="1" pc="1.2250" />
 <rate service="Priority" iso="DE" kg="1" pc="1.1140" />
 <rate service="Priority" iso="GB" kg="1" pc="1.4300" />

 <rate service="Express" iso="FR" kg="0.1" pc="64.6400" />
 <rate service="Express" iso="CA" kg="0.1" pc="101.0000" />
 <rate service="Express" iso="DE" kg="0.1" pc="129.2800" />
 <rate service="Express" iso="GB" kg="0.1" pc="147.6380" />
 <rate service="Express" iso="GB" kg="0.15" pc="220.7260" />
 <rate service="Express" iso="DE" kg="0.15" pc="193.2800" />
 <rate service="Express" iso="CA" kg="0.15" pc="151.0000" />
 <rate service="Express" iso="FR" kg="0.15" pc="96.6400" />
 <rate service="Express" iso="FR" kg="0.2" pc="128.6400" />
 <rate service="Express" iso="CA" kg="0.2" pc="201.0000" />
 <rate service="Express" iso="DE" kg="0.2" pc="257.2800" />
 <rate service="Express" iso="GB" kg="0.2" pc="293.8140" />
 <rate service="Express" iso="GB" kg="0.25" pc="366.9020" />
 <rate service="Express" iso="DE" kg="0.25" pc="321.2800" />
 <rate service="Express" iso="CA" kg="0.25" pc="251.0000" />
 <rate service="Express" iso="FR" kg="0.25" pc="160.6400" />
 <rate service="Express" iso="FR" kg="0.3" pc="192.6400" />
 <rate service="Express" iso="CA" kg="0.3" pc="301.0000" />
 <rate service="Express" iso="DE" kg="0.3" pc="385.2800" />
 <rate service="Express" iso="GB" kg="0.3" pc="439.9900" />
</xml>

And my XSL so far...
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:key name="service" match="rate" use="@service" />
<xsl:key name="iso" match="rate" use="@iso" />

<xsl:variable name='ratelist' select='//rate'/>

<xsl:template match="/">
<xml>

    <xsl:variable name='servicelist' select="$ratelist[generate-id()=generate-id(key('service', @service))]"/>
    <xsl:for-each select='$servicelist'>

        <xsl:variable name='servicerate' select="$ratelist[@service=current()/@service]"/>

        <xsl:variable name='isolist' select="$servicerate[generate-id()=generate-id(key('iso', @iso))]"/>

<xsl:value-of select='@service'/>

            <xsl:for-each select='$isolist'>

                    <xsl:value-of select='@iso'/>

            </xsl:for-each>

    </xsl:for-each>
</xml>
</xsl:template>
</xsl:stylesheet>

A: As I mentioned in the comments, this is not a trivial undertaking. See if you can make sense of the following stylesheet:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:key name="rate-by-service" match="rate" use="@service" />
<xsl:key name="rate-by-country" match="rate" use="concat(@service, '|', @iso)" />
<xsl:key name="rate-by-weight" match="rate" use="concat(@service, '|', @kg)" />
<xsl:key name="value" match="rate" use="concat(@service, '|', @iso, '|', @kg)" />

<xsl:template match="/xml">

        <xsl:for-each select="rate[generate-id() = generate-id(key('rate-by-service', @service)[1])]">
            <xsl:variable name="group" select="key('rate-by-service', @service)" />
            <xsl:variable name="service" select="@service" />

            <xsl:variable name="countries" select="$group[generate-id() = generate-id(key('rate-by-country', concat(@service, '|', @iso))[1])]"/>

            <xsl:variable name="weights" select="$group[generate-id() = generate-id(key('rate-by-weight', concat(@service, '|', @kg))[1])]"/>

                <xsl:value-of select='@service'/>

                        Country

                        <xsl:for-each select="$weights">

                                <xsl:value-of select='@kg'/>

                        </xsl:for-each>

                    <xsl:for-each select="$countries">
                        <xsl:variable name="iso" select="@iso" />

                                <xsl:value-of select='@iso'/>

                            <xsl:for-each select="$weights">

                                    <xsl:value-of select="key('value', concat($service, '|', $iso, '|', @kg))/@pc"/>

                            </xsl:for-each>

                    </xsl:for-each>

        </xsl:for-each>

</xsl:template>

</xsl:stylesheet>

when applied to your input example, this will produce:
Result

Standard

            Country
            0.1
            0.15
            0.2
            0.25
            0.3

            FR
            202.0000
            302.0000
            402.0000
            502.0000
            602.0000

            CA
            101.0000
            151.0000
            201.0000
            251.0000
            301.0000

Priority

            Country
            0.5
            0.75
            1

            CA
            0.6000
            0.8500
            1.1000

            FR
            0.6680
            0.9470
            1.2250

            DE
            0.6070
            0.8610
            1.1140

            GB
            0.7800
            1.1050
            1.4300

Express

            Country
            0.1
            0.15
            0.2
            0.25
            0.3

            FR
            64.6400
            96.6400
            128.6400
            160.6400
            192.6400

            CA
            101.0000
            151.0000
            201.0000
            251.0000
            301.0000

            DE
            129.2800
            193.2800
            257.2800
            321.2800
            385.2800

            GB
            147.6380
            220.7260
            293.8140
            366.9020
            439.9900

Rendered:


text:
Q: What effect, if any, does talking to your players have? In the 2006 PS2 game Let's Make a Soccer Team!, one of the menu options is labelled "Talk To". Every in-game day, you can talk to four or five of your players, triggering a short cutscene in which they tell you one of several preset lines (the main one I remember being "This formation... I don't really get it.")
I've been playing the game on-and-off for years now, and I choose this option more or less every chance I get, but it's recently occurred to me that I don't know what it actually does. Does talking to your players have any in-game effect, or is it just there as fluff?


text:
Q: How to store null in a double field in mongodb My mongodb schema has a field of "double" data type. Sometimes, when there is no value for this field, mongo is storing it as 0.0 but I need it to store as null

*

*db.nulltest.insertOne({ "name": "abc", "salary": null }) - When inserted, schema validation fails (which is expected)

*db.nulltest.insertOne({ "name": "abc", "salary": Number(null) }) - When inserted, stores as 0.0 ("salary" : 0.0)

*db.nulltest.insertOne({ "name": "abc", "salary": Number() }) - When inserted, stores as 0.0 ("salary" : 0.0)

*db.nulltest.insertOne({ "name": "abc", "salary": Number("null") }) - When inserted, stored as NaN ("salary" : NaN)
My Schema:
db.createCollection("nulltest", {
validator: { $jsonSchema: {
    bsonType: "object",
    properties: {
        "name": {
            bsonType: "string"
        },
        "salary": {
            bsonType: "double"
            }
        }}
    }} )

Question: How can I store null value in a field of double data type? ie: "salary": null

A: You can use an array for bsonType. For example:
db.createCollection("test", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["num"],
      properties: {
        num: {
          bsonType: [ "double", "null" ]
        }
      }
    }
  }
})

This schema should accept double or null:
> db.test.insert({_id: 0, num: 123})
> db.test.insert({_id: 1, num: null})
> db.test.find()
{ "_id": 0, "num": 123 }
{ "_id": 1, "num": null }

All possible types are outlined in BSON types.
Note that null is a separate type. Number(null) doesn't make sense from types point of view. It's like saying Number(String).


text:
Q: Access denied for user 'root'@'localhost' (using password yes) MariaDB пришлось поменять сервер, и тут возникла проблема с подключением к базе данных, а если быть точнее, то с подключением из Laravel.
На старом сервере была MySQL 8.0, тут же MariaDB 10.5.15, вроде как они работают на одном драйвере, но может быть ошибаюсь.
Команды в терминале выглядят вот так:
mysql -u root
use table;
select * from users;

Всё работает правильно, как и нужно.
PhpMyAdmin тоже работает правильно, а вот сайт:
SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) (SQL: select * from `users` where `email` = 123@gmail.com limit 1)

Получается как-то так, пробовал выдавать права (хотя не понимаю зачем, это же root), пробовал:
ALTER USER 'root'@'localhost' IDENTIFIED VIA mysql_native_password USING PASSWORD('root');
Никак не помогает, пробовал создавать новых пользователей - тоже не работает, как я понимаю вся проблема именно в подключении из Laravel,
'mysql' => [
            'driver' => 'mysql',
            'url' => env('DATABASE_URL'),
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'forge'),
            'username' => env('DB_USERNAME', 'forge'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => extension_loaded('pdo_mysql') ? array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ],

Этот код config/database.php я не менял, и по идее он должен работать, а по факту - нет.

A: Нашёл причину, но не понял смысла ошибки.
Как пытался подключиться Laravel
'mysql' '--host=111.11.11.111' '--port=3306' '--user=root' '--password=password' '--default-character-set=utf8mb4' 'datatable'

Правильное подключение
'mysql' '--host=localhost' '--port=3306' '--user=root' '--password=password' '--default-character-set=utf8mb4' 'datatable'

Вся проблема была в host, нужно указывать не IP адрес, а localhost


text:
Q: How to populate PeoplePicker control? I'm trying to use Javascript to populate a PeoplePicker control in Sharepoint 2013:
name="Engineer"
var ppDiv=$("[id$='ClientPeoplePicker'][title='"+name+"']");
console.log(ppDiv.html());
var ppEditor=ppDiv.find("[title='"+name+"']");
var spPP=SPClientPeoplePicker.SpClientPeoplePickerDict[ppDiv[0].id];
ppEditor.val("Abc, Xyz");
spPP.AddUnresolvedUserFromEditor(true);

Two problems:  ppDiv is still undefined after the assignment statement, and SPClientPeoplePicker is not defined; according to this article, it's defined by clientpeoplepicker.js, which is a script that's supposed to be loaded on every page that has a People Picker.
EDIT:
I changed the code to:
name="Engineer"
var ppDiv=$("div[title='"+name+"']");
console.log(ppDiv.html());
var ppEditor=ppDiv.find("[title='"+name+"']");
var spPPD=SPClientPeoplePicker.SpClientPeoplePickerDict;
console.log(spPPD[0]);
var spPP=spPPD[ppDiv[0].id];
ppEditor.val("Abc, Xyz");
spPP.AddUnresolvedUserFromEditor(true);

Now ppDiv is defined (as shown by its HTML successfully appearing in the console log), but it's crashing on the line var spPPD=SPClientPeoplePicker.SpClientPeoplePickerDict; with this error:
Uncaught ReferenceError: SPClientPeoplePicker is not defined

A: Here is how i did it. With fieldName beeing the column title of the people picker and userAccountName the user login name/last part of the claim.
One thing to point out is that it has to be a client people picker. As far as i know, sharepoint uses server side people picker by default in custom forms so make sure its really a client people picker.
function SetAndResolvePeoplePicker(fieldName, userAccountName) {

var controlName = fieldName;

var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");

var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");

var spPeoplePicker =   SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];

peoplePickerEditor.val(userAccountName);

spPeoplePicker.AddUnresolvedUserFromEditor(true);

//disable the field

spPeoplePicker.SetEnabledState(false);

//hide the delete/remove use image from the people picker

$('.sp-peoplepicker-delImage').css('display','none');

}

A: I find that if I add a 500-700ms delay before calling the code, that I do not get this error:

window.setTimeout(function() {
      SetAndResolvePeoplePicker("PickerFieldName", "emailAddress@company.com");
      }, 750);

    function SetAndResolvePeoplePicker(fieldName, userAccountName) {
      var controlName = fieldName;
      var peoplePickerDiv = jQuery("[id$='ClientPeoplePicker'][title='" + controlName + "']");
      var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");
      var spPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];
      peoplePickerEditor.val(userAccountName);
      spPeoplePicker.AddUnresolvedUserFromEditor(true);
    }


text:
Q: Using LINQ to Entities dynamic JOIN So say you have a table of Keywords.  For simplicity sake lets just say it has 2 fields an Id integer, Keyword varchar(100).  A query comes in for multiple keywords.  For example a query for "quick brown fox".  The requirement would be that we will take any records where the Id selected contains at least once occurrence of all three keywords. Moreover, it can be a partial match using the StartsWith.  I can use the PredicateBuilder to build the multiple OR clauses that will ultimately be needed but to also filter these records, I would need to execute a JOIN on the same table for each keyword. I should note that the Id field is not unique and can have multiple entries.
The SQL Looks more or less like this or should
select k1.Id
  from Keywords k1
 inner join Keywords k2 on k1.Id = k2.Id
 inner join Keywords k3 on k2.Id = k3.Id
 where k1.Keyword like @k1
   and k2.Keyword like @k2
   and k3.Keyword like @k3

The LINQ that I have so far would be
var predicate = PredicateBuilder.False<Keyword>();
foreach (string term in searchTerms)
{
   string temp = term;
   predicate = predicate.Or(p => p.Keyword.StartsWith(temp));
}
var keys = Keywords.AsExpandable().Where(predicate).ToList();

This will produce SQL that more or less looks like:
SELECT
[Extent1].[Id] AS [Id]
FROM  [dbo].[Keywords] AS [Extent1]
WHERE ([Extent1].[Keyword] LIKE @p__linq__1 ESCAPE '~') OR ([Extent1].[Keyword] LIKE @p__linq__2 ESCAPE '~') OR ([Extent1].[Keyword] LIKE @p__linq__3 ESCAPE '~')

In order to use this result I would then have to do a DistinctBy and then JOIN back to my results.  This can produce a huge memory requirement and I am trying to find a solution that does most of what I want on the server.

A: To rephrase your query, you're looking for the ID values such that a group of all of the keywords for that ID contains all of the search terms that you're looking for.
Rather than trying to use Join to create a group of all of the keywords for an ID, you can use GroupBy, and then when you have the group of all keywords sharing an ID it's simple enough to filter out only the ones in which the group contains all of the search terms.
var query = keywords.GroupBy(keyword => keyword.Id)
    .Where(group => searchTerms.All(term =>
        group.Any(keyword => keyword.Keyword.StartsWith(term)))
    .Select(group => group.Key);

A: Ultimately I was able to get it to produce the SQL I was looking for.  Even though the likelyhood that this issue is unique to me, I will post my solution.  Perhaps it will be useful to someone.
LINQ
var term = searchTerms[0];
var keys = Keywords.Where (k => k.keyword.StartsWith(term));
for(var i=1; i < searchTerms.Length; i++)
{
    var searchTerm = searchTerms[i];
    keys =
        from k1 in keys
        join k2 in Keywords on k1.Id equals k2.Id
        where k2.keyword.StartsWith(searchTerm)
        select k1;
}

PRODUCED SQL:
-- Region Parameters
DECLARE @p__linq__0 VarChar(1000) = 'the%'
DECLARE @p__linq__1 VarChar(1000) = 'brown%'
DECLARE @p__linq__2 VarChar(1000) = 'fox%'
-- EndRegion
SELECT
    [Extent1].[Id] AS [Id]
    FROM    [dbo].[Keywords] AS [Extent1]
    INNER JOIN [dbo].[Keywords] AS [Extent2] ON [Extent1].[Id] = [Extent2].[Id]
    INNER JOIN [dbo].[Keywords] AS [Extent3] ON [Extent1].[Id] = [Extent3].[Id]
    WHERE ([Extent1].[keyword] LIKE @p__linq__0 ESCAPE '~') AND ([Extent2].[keyword] LIKE @p__linq__1 ESCAPE '~') AND ([Extent3].[keyword] LIKE @p__linq__2 ESCAPE '~')

Of course I would put some checking to make sure that I have more than 1 searchTerm before beginning my loop.  But you get the picture.


text:
Q: SQL query only selecting first result I want to retrieve all songIDs that are associated with the userID that I input but it only prints the first result.
database:

My code:
enter = raw_input('Enter UserID: ')
cursor = MusicData.cursor()
sql = "SELECT * FROM (SELECT songID FROM train WHERE userID=? )"
result = cursor.execute(sql,(enter,))
print result.fetchall()[0][0],

Enter UserID: 3a613180775197cd08c154abe4e3f67af238a632
SODOZXB12A8C13CD55

A: You're only showing the first rows first column due to
[0][0] after in this line print result.fetchall()[0][0]

A: Add "LIMIT NN" to your SQL request. That will limit an output to NN number of rows:
sql = "SELECT * FROM Table LIMIT 5"

Will give you only 5 rows.
on MS SQL DB it should be the "TOP" keyword:
sql = "SELECT TOP 5 * FROM Table"

A: I fixed it by adding a for loop of fetchall()
rows = result.fetchall()
for row in rows:
    print row

A: The problem is with your print statement. Right now by giving print result.fetchall()[0][0] you are asking python to print one element.  Use
for item in result.fetchall():
    print item


text:
Q: About square matrix and Jordan's Canonical form Let $A$ a nonderogatory matrix and $B$ that commutes with $A$. How can I show that exists a polinomyal $p(x)$ such that the set of the eigenvalues of $B$ can be expressed as $\{p(\lambda_i): \lambda_i\in\sigma (A)\}$, where $\sigma(A) $ is the spectrum of $A$.\
I have, with the same hipoteses, exists a polynomial $p(x)$ such that $B=p(A)$ but I don't kmow how to use it.

A: Fact 1: $A$ is non-derogatory (the minimum pol. of $A$ is the characteristic pol. of $A$) IFF $AB=BA\Leftrightarrow B$ is a polynomial in $A$.
FACT 2: Let $A$ be any square matrix and $p$ be any polynomial. If $spectrum(A)=(\lambda_i)_i$, then $spectrum(p(A))=(p(\lambda_i)_i$. Proof: triangularize the matrix $A$.


text:
Q: How can I process multiple Google Places API results after all the callbacks have completed? I have an array that contains location results from the Google Geocode and Places JavaScript API.
Any elements in this array from the Place results contain the place_id value which I'd like to utilise to get further basic information about that place.
The initial array (uniqueGeoRes) may contain up to 7 results.
I am confused between the Places API Service and Callback, and how to implement a callback when all of the elements of uniqueGeoRes have been checked for additional Places data.
For example, if all 7 elements of uniqueGeoRes have a place_id I need to use the Places Service to get additional information on each element.
The loop to do this is completing before the Places callbacks are complete because the outer function is not asynchronous.
I think a promise might have helped, but I'm limited to ES3. Here's what I have so far.
This doesn't give the expected results because by the time the callback has completed the value  i has already met that of q, even on the first callback.
I've gotten myself totally lost!
How can I ensure the Places callbacks are complete before doing anything with the newly populated addrOutput array?
var q;
q = 7;

// Set the size of the results array (q is hardcoded maximum value)
if (uniqueGeoRes.length < q) {
    q = uniqueGeoRes.length;
}
uniqueGeoRes.length = q;
var addrOutput = [];

//Check for additional Places data
function updatePlace(arr, callback1){

    console.log('asyncFunction has been called');
    console.log('processing: ', arr);

    for (var i = 0; i < q; i++) { // each element in the uniqueGeoRes array

        if (arr[i].source = 'Places API') {
        // Append extra information from the Place look up on individual place_id

            console.log('Getting additional information for PLACES result: ' + arr[i].place_id);

            var request = { placeId: uniqueGeoRes[i].place_id, fields: ['address_component', 'formatted_address', 'geometry', 'name'] };
            service.getDetails(request, callback);

            function callback(place, status) {  // Get the additional place information.

                if (status == google.maps.places.PlacesServiceStatus.OK) {

                    addrOutput.push(place);
                    console.log ('Loop is ' + i + '/' + q + '. addrOutput length is now: ' + addrOutput.length);

                    if (i === q) {
                        callback1()
                    }

                } else {
                    console.warn ('Place Service Status is bad.');
                }

            }

        }
    }

};

// Call when asyncFunction completes
function callback1(error) {
  if (!error) console.log('asyncFunction is complete');
}

updatePlace(uniqueGeoRes, callback1);

This is the current output
[Log] asyncFunction has been called (development, line 817)
[Log] processing:  – [Object, Object, Object, …] (7) (development, line 818)
[Object, Object, Object, Object, Object, Object, Object]Array (7)
[Log] Getting additional information for PLACES result: ChIJwSc0D-zih0gR2uOIFj2UCv8 (development, line 824)
[Log] Getting additional information for PLACES result: ChIJr_4dcTH9h0gRl1OqMr4OSec (development, line 824)
[Log] Getting additional information for PLACES result: ChIJ9wqvVQ7jh0gRPYUz575U0Bs (development, line 824)
[Log] Getting additional information for PLACES result: ChIJBw3rDLXih0gRivw-FONRgZU (development, line 824)
[Log] Getting additional information for PLACES result: ChIJ774cdbXih0gRwWCg-MxTKjs (development, line 824)
[Log] Getting additional information for PLACES result: ChIJwQnvs5Pih0gR125FEtKwli0 (development, line 824)
[Log] Getting additional information for PLACES result: ChIJXyhtsZPih0gRIZgUPLvv_Ws (development, line 824)
[Log] Loop is 7/7. addrOutput length is now: 1 (development, line 835)
[Log] asyncFunction is complete (development, line 854)
[Log] Loop is 7/7. addrOutput length is now: 2 (development, line 835)
[Log] asyncFunction is complete (development, line 854)
[Log] Loop is 7/7. addrOutput length is now: 3 (development, line 835)
[Log] asyncFunction is complete (development, line 854)
[Log] Loop is 7/7. addrOutput length is now: 4 (development, line 835)
[Log] asyncFunction is complete (development, line 854)
[Log] Loop is 7/7. addrOutput length is now: 5 (development, line 835)
[Log] asyncFunction is complete (development, line 854)
[Log] Loop is 7/7. addrOutput length is now: 6 (development, line 835)
[Log] asyncFunction is complete (development, line 854)
[Log] Loop is 7/7. addrOutput length is now: 7 (development, line 835)
[Log] asyncFunction is complete (development, line 854)

A: forkJoin can help in this scenario. Using forkJoin, we can have collection of observables and callback function when all observables are completed. Below links may help with samples
https://rxjs-dev.firebaseapp.com/api/index/function/forkJoin
https://stackblitz.com/edit/typescript-c3f62b?file=index.ts&devtoolsheight=100
Similar functionality can be achieved using Promise.all
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all


text:
Q: Is there a method that always gets called right after didSelectRowAtIndexPath? I'm working on an iPad app in which I have a table view.  When the user selects a row in the table, I use didSelectRowAtIndexPath to open a popover.  I'm getting an error message saying "message sent to deallocated instance" when I try to use a certain button.  I originally though the errors was getting thrown by the popover (in it's viewDidLoad or something), so I put a breakpoint in and stepped through the code.  To my surprise, I was able to step all the way through the loading of the popover and the rest of the didSelectRowAtIndexPath on my table view (which actually just involves stepping out of some if blocks).  The error then gets thrown when I get a couple steps into the automatically generated code that doesn't appear in any of my class files (that looks like 0x0010d71d <+1164> mov 0x6...).
So, my question is, how do I find where this error is being thrown?  Is there another method that is automatically run after didSelectRowAtIndexPath that could be getting messed up somewhere?

A: Enable NSZombieEnabled in your DEBUG build (see How do I set up NSZombieEnabled in Xcode 4?) to locate instances of objects you're accessing that have been deallocated/released.
Also, consider upgrading your project to ARC, which will likely resolve memory management issues like this.

A: Okay, everyone's responses lead me to find malloc error -[CFString release], which helped me figure out I had a string in my popover that I alloc in viewDidLoad by
myString = [NSMutableString stringWithString:[myGlobalFunctionClass getMyString]];

Since I alloc it this way, it gets set to autorelease.  The problem was I was explicitly [myString release]; and myString = nil; in viewWillAppear.  Removing the release and =nil parts cleaned up my error.
To answer the actual question that I posted, I believe the autorelease wasn't firing until the simulator actually tried to display the popover (which would run after didSelectRowAtIndexPath).  Since that occurs after I explicitly [myString release] in viewWillAppear, it was trying to autorelease something that was no longer there.  Just to reiterate, the proper way to do it was let it autorelease at the end, and not [myString release] anywhere in my code.
Can someone verify that this is correct?  As I mentioned in my comments, I'm still very new to iOS development.  I have a feeling at the end of this project, I'm going to be able to go back to first stuff I did in it and make dozens of improvements in terms of doing things more efficiently and more in accordance with best practice.


text:
Q: All items in list are identical? I some lines of code in order to prep the data to be sorted. In order to do this, I needed each item in the list to be a list. For example, if my list was [a, b, c, d], the list should be become [[a], [b], [c], [d]] where a, b, c, and d are integers. My code however returns [[d], [d], [d], [d]]:
len_of_list = random.randint(8500, 10000)
val_list = range(len_of_list)

list_one = [[-1]]
for index in range(0, len_of_list):
    list_one[0][0] = val_list[index]
    val_list[index] = list_one[0]
print val_list

The weirdest thing that happens to the code is that when the second-to-last line is replaced with val_list[index] = list_one[0][0], it returns the correct values just without the []. Thus I assumed that removing the last [0] would return the values with the [] around them. But what is returned was the last integer in the list originally surrounded by [] for all values. This shouldn't happen because list[0][0] is reset every iteration with list[0][0] = val_list[index].
So why is the list being returned as [[d], [d], [d], [d]] instead of [[a], [b], [c], [d]]. Of course, the list has at least 8500 unique integers but d represents the last value in the list or put simply d = val_list[len(val_list) - 1].

A: Try this:
[[x] for x in myList]

A: You put list_one[0] in val_list[index]. Since list_one[0] is a list, val_list[index] receives its address, not its value. Therefore, when the value of list_one[0] is changed, ie. at every iteration, the value of val_list[index] for every index is changed as well.
Thus, the final value contained at every index of the list is the last one, [d].
This happens because list_one[0] is a list, which is mutable.

Beyond this fact, your code is not really pythonic. First, you build an empty list of length len_of_list by writing val_list = range(len_of_list). While this works in Python 2, it does not in Python 3, because a range object is semantically different from a list. Besides, a list should be built by appending or inserting elements, but not by making a long enough empty list and then filling the indices.
Then, you are using complicated code to build your list of list, while the following would have been enough:
for index in range(len_of_list):
    val_list[index] = [index]

A more basic pythonic way to do the same, with append, would be:
len_of_list = random.randint(8500, 10000)
val_list = list()

for index in range(len_of_list):
    val_list.append([index])

However, the most pythonic way would be to use a list comprehension. If you have l = [a, b, c, d], and you want to have [[a], [b], [c], [d]], the fastes is the following:
[[elt] for elt in l]


text:
Q: Downloading an excel file from a link in python I had link called "Click here to download" on an a page and its HTML form is

 Click here to download all records.

When i clicked on "Click here to download" an excel file is downloaded, Actually i need to find the url of the link to download excel file.
And i had the javascript function with the code below
function CallExcelFunction() {
    var hidInd = document.getElementById('hidInd');
    var hidFromDate = document.getElementById('hidFromDate');
    var hidToDate = document.getElementById('hidToDate');
    var hidDMY = document.getElementById('hidDMY');
    window.open('indices_main_excel.aspx?ind=' + hidInd.value + '&fromDate=' + hidFromDate.value + '&toDate=' + hidToDate.value + '&DMY=' + hidDMY.value, '_blank',
'toolbar=yes,location=no, directories=no, status=no, menubar=yes,scrollbars=yes, resizable=yes ,copyhistory=no, width=800, height=600');
}

can anyone please clear this data, thanks in advance

A: When you click on that button, a javascript function is invoked, and that probably redirects to the file.
To be able to download the file with python, you either need to find the link on your own (if you are always downloading the same file), and then use urllib. For that, you could read the javascript code.
Or you need to use some browser automation tool (through python for example), like selenium: http://seleniumhq.org/


text:
Q: Select multiple  keeping track of selected elements I get the feeling I'm on the wrong track after several days here.
Trying to use a <select> to keep track of multiple client choices.
<div id="ajax">
<select id="select_site" name="site" multiple>
    <option value="" selected>checked</option>
    <option value="" selected>checked</option>
    <option value="">unchecked</option>
    <option value="">unchecked</option>
</select>
<button id="continue" type="button">Save</button>
</div>

desired result:
click checked alert('subtract from checked')
click unchecked alert('add to checked')
$('#ajax').on('click', '#select_site option', function () {
  var checked = $('#select_site option:selected');
  if ($(this).prop('selected') == 'selected') {
    alert('subtract from checked');
  } else {
    alert('add to checked');
  }
  $('#select_site').empty();
  $.each(checked, function (i, v) {
    $('#select_site').append(v);
  });
  });

$('#ajax').on('click', '#continue', function () {
  var checked = $('#select_site option:selected');
  alert(checked);
});

jsFiddle
Thanks for any help!

A: There is some mistakes in your script.
1: It will not be on mouse click, but on mousedown so you can preevnt default behavior.
2: As i said, you need to prevent default behavior, so you nned this :
pseudo-on(function(e){
    e.preventDefault()
    //Your code
})

3: Using .prop() return a boolean, so at the moment, your condition is always false. Your condition can simply be if ($(this).prop('selected'))
4: Since the default behavior is prevented, you need to manually add or delete a selected option.
5: Because you manually select options, the var checked must be declared.
6: I don't know what you meant to do with the .each() loop with the append, but i don't think you'll need it with my solution. The var checked will aswell be useless in this case.
Here a working fiddle : http://jsfiddle.net/akshC/1/


text:
Q: w3wp.exe The process was terminated due to an unhandled exception - Random restarts We have an asp.net running on IIS 7.5 with elmah error logging. Randomly we get these two event logs at the same time (same second) reporting w3wp restart which logs everyone out. These errors don't make it to elmah, even though elmah logs everything else.
The errors are random, it's not a specific error that causes these w3wp restarts. One error was a failure sending an email because the smtp server timed out. Another error was a null reference exception.
I notice there's a problem when people complain call to say they've been logged out and when I check the event log I see these errors but by then w3wp restarted already and running fine. There's really nothing in the details to help.
This seems to happen under heavy load, when the website is used most heavily but RAM/CPU etc are all fine on the server and I can't find anything else reported at the same time regarding RAM or anything else.
It's not the "rapid fail protection" because the application gets a handful of exceptions a day and the "Rapid Fail" is set to 5 errors in 5 mins, so it's not that either. Never had 5 errors in 5 mins.
These errors don't get reported by elmah so it's almost like the app crashes before the exception can be handled, which I don't understand how.
Also event log sometimes has this log at about the same time (within few seconds) but not for every restart.

A process serving application pool '' suffered a fatal communication
  error with the World Wide Web Publishing Service. The process id was
  ''. The data field contains the error number.

So any ideas what I can check? It occurs randomly, sometimes every few weeks, sometimes 4 times a week.
Source = .NET Runtime:

Application: w3wp.exe Framework Version: v4.0.30319 Description: The
  process was terminated due to an unhandled exception.

Source = ASP>NET 4.0.30319

An unhandled exception occurred and the process was terminated.
  Application ID: /LM/W3SVC/6/ROOT Process ID: 33264


text:
Q: Group by with condition pandas I have a dataframe with 4 columns - name, date, location, amount. My goal is to create a new column called flag. For every row I am trying to look back 52 weeks from that date and if the 52 week lag amount is greater than the current row amount then flag=1 else flag=0. If the look back date 52 weeks ago is not found in the data then it should assign the flag as 0 for that row. This comparison should happen at a group by level of name and location. Date field is in the date format.
UPDATE:
I meant, for a combination of name and location there may be multiple rows. e.g. john and CHI there are two rows. one with date 5/08/22 and one with 5/09/21 (which is 52 weeks ago). I want to compare these rows and then find out if the more recent row amount is greater than 52 weeks ago and populate the flag accordingly. I have populated the flags for demonstration of the output.
sample df:

name
date
location
amount
flag

John
5/08/22
CHI
50
0

John
5/09/21
CHI
40
0

Mike
4/24/22
LAS
30
1

Mike
4/25/21
LAS
40
0

John
4/25/22
ORL
50
0

I am currently using lambda function but its taking a long time to run. Can someone help me out.

A: This may work:
df['offset'] = df['date'] - pd.DateOffset(weeks=52)
df['calc'] = df['offset'].isin(df['date'])
df['calc'][df.calc == True]= 1
df['calc'][df.calc == False]= 0

Although I'm not sure what you mean by:
"and if the 52 week lag amount is greater than the current row amount", if 52 is greater than [50,40,30,40,50]?


text:
Q: What is the best sorting algorithm to sort an array of small integers? As per question title, if the array is of an odd length and the array elements are numbered 1 - 10.
Example,

3 6 8 1 3 7 7 9 4 1

I was thinking of using heapsort? Since it is an array, merge sort and insertion sort requires shifting, and would not be so efficient.

A: This is my counting sort example
static int[] countingSort(int[] numbers) {
    int max = numbers[0];
    for (int i = 1; i < numbers.length; i++) {
        if (numbers[i] > max)
            max = numbers[i];
    }

    int[] sortedNumbers = new int[max+1];

    for (int i = 0; i < numbers.length; i++) {
        sortedNumbers[numbers[i]]++;
    }

    int insertPosition = 0;

    for (int i = 0; i <= max; i++) {
            for (int j = 0; j < sortedNumbers[i]; j++) {
                    numbers[insertPosition] = i;
                    insertPosition++;
            }
    }
    return numbers;
}

A:
the array elements are number from 1 - 10.

With this restriction, counting sort will be far more efficient than any general purpose sorting algorithm - it's O(n)

A: If there are only 10 elements it isn't worth your while to even worry about it. If there are a million it might start to become significant.

A: Edit: A counting sort is probably optimal given the constraint that the elements only range from 1-10. A counting sort applied to this problem will run in O(n) time. A merge sort (as I recommended below) will run in no better than O(nlogn) time. Parallelizing a counting sort could be interesting. Simply assign a subarray with n/p elements to each processor. Each processor would have its own count array of size 9. This step should take O(n/p) time. Then consolidate all the count arrays into a single array, which should take O(p) time. I haven't fully thought through the last step in the counting sort where the elements are placed in order, but it seems as long as the elements of the count array are atomic, you could assign n/p sections of the original array to individual processors and achieve some parallelization. There would be contention at individual elements of the count array, however, potentially substantially reducing concurrency. You might be able to assign subsections of the count array to p processors and you are back to O(n/p) runtime, if the elements are distributed fairly evenly, but you would be limited to 10 processors. If the elements are not distributed evenly, one or more processors could be doing a larger proportion of the work. This is great question; can you do a counting sort in O(n/p) time?
Quicksort is a great in-place sort algorithm that runs fast and conserves memory. However, given the elements only range from 1-10, if you are sorting large numbers of elements, you will end up with large runs of the same number, either initially, or at interim times during the sort. In-order arrays or sub-arrays can really bog down a Quicksort's performance.
If you don't care about memory, a simple Mergesort would suffice. Mergesort is up there with the fastest standard sort algorithms.
The default Collections.sort() implementation in Java 7 is a Mergesort algorithm adapted from 'TimSort.' The default Arrays.sort() implementation in Java 7 is a dual pivot Quicksort.
If you would like to go parallel, a Parallel Quicksort can achieve good results on large arrays with small numbers of processors, but with the same limitations as the sequential Quicksort. PSRS can help scale to larger numbers of processors.

A: You should consider looking at this for complexity chart Complexity Comparison Chart.
The comparison of sorting algorithm is based on their Best, Average, Worst case scenario for time and space complexity.Based on this chart you can see Counting Sort approach is best on both space and time complexity. Other comparable method is Radix Sort.
Worst [Time,Space] complexity of "Counting Sort" :- [O(n+k),O(k)].
Worst [Time,Space] complexity of "Radix Sort" :- [O(nk),O(n+k)].

A: this is an example of simple sort (Insertion sort)
private static void insertionSort(int[] a) {

    // [230, 23, 45, 34, 98]
    for (int j = 2; j < a.length; j++) {

        int key = a[j];
        int i = j - 1;

        while (i > 0 && a[i] > key) {
            a[i + 1] = a[i];
            i--;
        }
        a[i + 1] = key;
    }

    System.out.println("sorted array: " + Arrays.toString(a));
}

A: Counting sort will be best in this scenario.
Assuming the data are integers, in a range of 0-k. Create an array of size K to keep track of how many items appear (3 items with value 0, 4 items with value 1, etc). Given this count, you can tell the position of an item — all the 1's must come after the 0's, of which there are 3. Therefore, the 1's start at item #4. Thus, we can scan the items and insert them into their proper position.
Creating the count array is O(N)
Inserting items into their proper position is O(N)
I oversimplified here — there is a summation of the counts, and a greatest-to-least ordering which keeps the sort stable.

A: QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot and then repeats the process. There are many different versions of quickSort that pick pivot in different ways


text:
Q: How I can Replace main() in already-compiled application? I need additional initialization over existing in dynamic-linked application.

A: If you want to hook additional code before running main() in an already-compiled program, you can use a combination of the constructor attribute, and LD_PRELOAD like so:
#include <stdio.h>

void __attribute__((constructor)) init() {
    printf("Hello, world!\n");
}

Compile and run:
$ gcc -shared demo_print.c -o demo_print.so -fPIC
$ LD_PRELOAD=$PWD/demo_print.so true
Hello, world!

If you don't want to run normal main() at all, just terminate (with exit() etc) before main() runs. Note that you won't be able to actually get the address of main() to call manually - just return from your constructor to continue normal startup.

A: If you're writing a shared library that needs specific startup initialisation, you can use the GCC "constructor" extension:
void foo() __attribute__ ((constructor))


text:
Q: Adwhirl Ads in Ipad Hi  I am Developing a universal App.i am showing adWhirl Ads on Iphone.its Working Fine
Now i want to display the Ads in Ipad.i have small doubts regarding this...
1)Is there any Configuration changes in Adwhirl For Ipad
2)Can I use Same Adwhirl Api For Iphone And Ipad
3)How can i Change Frames specific to ipad

Can Any one help me to get out of this

A: I did exactly what you want to do and I wrote a tutorial for others and for myself to remember what I did.
Here it is: Universal Adwhirl (UIKit)
If you happen to be working on a cocos2d game take a look at this: Universal Adwhirl Ads in Cocos2d


text:
Q: Change selection color for text field I have two text fields inside of a form. When either input field is selected the outline for that field turns white. I need to change this color. How can I achieve this?
input[type=text], input[type=password] {
    width: 65%;
    padding: 12px 20px;
    padding-top: 10px;
    margin: 4px 85px;
    display: inline-block;
    border: 1px solid rgba(115, 82, 122, 0.486);
    box-sizing: border-box;
    background-color: rgb(33, 33, 34);
    color:rgba(175, 149, 35, 0.836);
    font-size: 18px;
    /* border-color: rgb(63, 15, 15); */
}

A: In the solution below, when the focus event of the <input> elements occurs, the border style is assigned a value and the border color of the <input> element is changed.

body {
  background-color: black;
}
input[type=text], input[type=password] {
    width: 65%;
    padding: 12px 20px;
    padding-top: 10px;
    margin: 4px 85px;
    display: inline-block;
    border: 1px solid rgba(115, 82, 122, 0.486);
    box-sizing: border-box;
    background-color: rgb(33, 33, 34);
    color:rgba(175, 149, 35, 0.836);
    font-size: 18px;
}
input[type=text]:focus, input[type=password]:focus {
  outline: none !important;
  border: 1px solid red;
}
<body>
  <form>
    <input type="text">
    <input type="password">
  </form>
</body>

A: Your version is still right. you can use with a class

body {
    background-color: #2a2f3f;
}
.text-control {
    display: block;
    width: 30%;
    padding: 0.375rem 0.75rem;
    font-size: 1rem;
    font-weight: 400;
    outline: none;
    line-height: 1.5;
    color: #0c3d13;
    background-color: #538976;
    background-clip: padding-box;
    border: 2px solid yellow;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    border-radius: 0.25rem;
    transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}
.text-control:hover {
    border: 2px solid green;
    background-color: red;
}
.text-control:focus {
    border: 2px solid #00ba4a;
    background-color: #1c6b3c;
}
<form>
    <input class="text-control" type="text" name="">
</form>


text:
Q: The Point of Using apply_filters() While i'm Trying To Develop a plugin, i tried to See some other plugin do the same stuff my plugin will achieve, then i saw The developer in the most functions work with the function apply_filters() and i didn't understand why .
This is an Example Below :
public static function myFunction() {
    return apply_filters( 'du/class/method' array(
        'index'    => 'value',
        'index'    => 'value',
        'index'    => 'value',
        'index'    => 'value',
    ) );
}

as you Can See in the first parameter in the function apply_filters() there is a string parameter, everywhere i see this function always i see something like du/class/method .
Please is There Any Explanation For That .

A: The point is to allow developers to customise aspects of your theme or plugin.
When calling apply_filters() you provide a name and a value that you want developers to be able to filter.
For your example:
$array = apply_filters( 'du/class/method' array(
    'index'    => 'value',
    'index'    => 'value',
    'index'    => 'value',
    'index'    => 'value',
) );

Developers can now change the value of $array in your plugin by using the du/class/method filter with add_filter(). To add an item, perhaps:
function wpse_303378_filter( $array ) {
    $array[] = 'New item';

    return $array;
}
add_filter( 'du/class/method', 'wpse_303378_filter' );

The name of the filter, in this case du/class/method can be whatever you want it to be, but many developers will 'namespace' it so it doesn't conflict with any other plugins. Advanced Custom Fields, for example, prefixes all its hooks with acf/. Your example implies that the filter name uses the class and method that it occurs in as a way to group related filters, but it will depend on the plugin.
You can read more about filters here.


text:
Q: Dividing a string in 2 parts and placing each part in a different new string I have a string (resultString) that contains long html codes. These codes are grouped in 2 main DIVs, window and Popup.
resultString = "
window content --- long html codes

Popup content --- long html codes
"

Now I want to retrieve the html content of window and popup DIVs separately and place them in 2 different strings (stringWindow and stringPopup).
stringWindow = "
window content --- long html codes
";
stringPopup = "
Popup content --- long html codes
";

Is there any simple way to do so in jQuery/javascript? The stringWindow is constructed in an Ajax json webmethod function. Any help is well appreciated! Thanks in advance.

A: You can use filter() and outerHTML

*

*Using filter you can filter element with certain selector

*Now you can use outerHTML for getting html content

var resultString = "
window content --- long html codes

Popup content --- long html codes
",
  stringWindow, stringPopup;

stringWindow = $(resultString).filter('#window')[0].outerHTML;
stringPopup = $(resultString).filter('#PopUp')[0].outerHTML;

console.log(stringPopup, stringPopup);

A: Trivial in jQuery:

var resultString = "
window content --- long html codes

Popup content --- long html codes
"

var $doc = $("
" + resultString + "
");
var stringWindow = $doc.find('#window').text();
var stringPopup = $doc.find('#PopUp').text();
console.log("window", stringWindow);
console.log("popup", stringPopup);

Not much harder in plain JS.
If by "Just the content" you don't mean "text" but markup inside the div, then replace text() with html().
EDIT: made into executable snippet.

A: A version that doesn't use jQuery, doesn't assume it is in the document or can be put into the document but still interprets it as HTML -
var domParser = new DOMParser(),
    doc = domParser.parseFromString(resultString, "text/html"),
    content = ["window", "PopUp"].map(function(id) {
        return doc.querySelector("#" + id).innerHTML;
    }),
    stringWindow = content[0],
    stringPopup = content[1];

A: Try this. It works for me. Demo
resultString = "
window content --- long html codes

Popup content --- long html codes
";

var res = resultString.split("
");

stringWindow = res[0].replace(/^
]*>|<\/div>$/g, '');
stringPopup = res[1].replace(/^
]*>|<\/div>$/g, '');

Hope It Helps.

A: I think this may help you :-
 var resultString = "
window content --- long html codes

Popup content --- long html codes
"
        var splitter = document.createElement('div');
        splitter.innerHTML = resultString;

        var window = $(splitter).find("#window")
        var poppup = $(splitter).find("#PopUp")

Mark as an answer if it helps

A: This is one way  to do it with C#...
It may help...
Given your result string as...
resultString = "
window content --- long html codes

Popup content --- long html codes
"

following should work..
string resultPopUp = resultString.Substring(resultString.IndexOf("<div id=\"PopUp"));
string resultWindow = resultString.Substring(resultString.IndexOf("<div id=\"window"), resultString.Length - resultString.IndexOf("
")+2);

Maintaining the string structure as
 this should work....

A: if you want just the content do somthing like this:
with jQuery:
 stringWindow =$('#window').innerHTML
 stringPopup =$('#PopUp').innerHTML

Only JS:
stringWindow =document.getElementById('window').innerHTML
stringPopup =document.getElementById('Popup').innerHTML


text:
Q: How can I edit my OpenShift php.ini and change the default socket to OPENSHIFT_MYSQL_DB_SOCKET How can I edit my php.ini and change the default socket to OPENSHIFT_MYSQL_DB_SOCKET?
I suppose a second question is why doesn't it match in the first place?
when I have my php program open the DB I get this error

Message: mysql_connect(): Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)

OpenShift MySQL socket env var is as follows:

OPENSHIFT_MYSQL_DB_SOCKET=/var/lib/openshift/517ab6855973cab1e200003d//mysql-5.1/socket/mysql.sock

Same config/code works find on my local system :-(

A: This does the trick in the CodeIgniter file (../application/config/database.php).
$openshiftsocket = getenv('OPENSHIFT_MYSQL_DB_SOCKET');
//echo "OpenShift socket is [$openshiftsocket]";

if (isset($openshiftsocket)) {
   echo 'foo';
   ini_set('mysql.default_socket', $openshiftsocket);
}


text:
Q: Grouping form errors in Play! Framework Is there an easy way to group form errors at the top of the form, rather than above each field?
Here is my Scala template:
@(registrationForm: Form[User])

@implicitField = @{ FieldConstructor(views.html.helper.twitterBootstrap2.twitterBootstrap2FieldConstructor.f) }

@import helper._

@helper.form(action = routes.Registration.index) {

    <fieldset>

        @if(registrationForm.hasGlobalErrors) {

            ×
                @registrationForm.globalError.message

        }

        <legend>Register</legend>

        @inputText(
            registrationForm("firstName"),
            '_label -> "First Name",
            '_showConstraints -> false,
            '_showErrors -> true,
            '_error -> registrationForm.error("firstName")
        )

        @inputText(
            registrationForm("lastName"),
            '_label -> "Last Name",
            '_showConstraints -> false,
            '_showErrors -> true,
            '_error -> registrationForm.error("lastName")
        )

        @inputText(
            registrationForm("emailAddress"),
            '_label -> "Email Address",
            '_showConstraints -> false,
            '_showErrors -> true,
            '_error -> registrationForm.error("emailAddress")
        )

        @inputPassword(
            registrationForm("password"),
            '_label -> "Password",
            '_showConstraints -> false,
            '_showErrors -> true,
            '_error -> registrationForm.error("password")
        )

        @inputPassword(
            registrationForm("password"),
            '_label -> "Confirm Password",
            '_showConstraints -> false,
            '_showErrors -> true,
            '_error -> registrationForm.error("password")
        )

    </fieldset>

    <button type="submit" class="btn">Register</button>

}

I have a custom validation that I'm doing to check for unique email address and based on that validation, I add an error to the global errors. I'd like to have any additional errors (that are thrown as a result of validation of other fields) grouped together with this error at the top of the form. Any suggestions?

A: In your @if(registrationForm.hasGlobalErrors){ you could always try calling registrationForm.globalErrors to get the List of all errors, traverse it, and output the message for each?
example:
@if(registrationForm.hasGlobalErrors){

         @for(validationError <- registrationForm.globalErrors){
              ×
              @validationError.message
         }

}

EDIT: At the request from the comments below I'm updating my answer to include an alternative method for grouping custom validation messages, which may not be the "best" solution but should accomplish just that.
In your controller:
if(filledForm.hasErrors()){

       for(String key : filledForm.errors().keySet()){
           List<ValidationError> currentError = filledForm.errors().get(key);
           for(ValidationError error : currentError){
               flash(key, error.message());
           }
       }
}

Or you could use an iterator, whichever you prefer.
And then in your view something along the lines of:
@if(flash.size() > 0){

        @for((key, value) <- flash){
            Error :  @value

        }

}

Like I mentioned, not the most elegant solution, but it should get a big list of your errors at the top of your page.

A: I have had also problems adding custom global errors to globalErrors and displaying them on the view.
My solution is use the errors object and add these global error under "global" key. Then in the view I display all "global" errors at the top.
My view:
@for(error <- form("global").errors) {

@error.message

}

My controller:
ValidationError error = new ValidationError("global", "User is not authorized.");
List<ValidationError> errors = new ArrayList<ValidationError>();
errors.add(error);
loginForm.errors().put("global", errors);
return badRequest(login.render(loginForm));


text:
Q: lov(list of value) in master detail I have oracle adf and jdeveloper.
I have a table with 3 columns that columns are lov(list of value).
these columns have master and details  relations .
I want to select master column and filtering details columns automaticaly.
can anyone help me ?


text:
Q: Doctrine Mapping DDD : Two or Many Entity to One Table Mapping on One Entity Manager I am following DDD and I have an Inquiry Context which have Marketer and Encoder entity. basically the two have the same data (they are the user of the system), but different logics (based on domain). I dont want to apply SINGLE TABLE INHERITANCE (it will add a discrimiator column) because the table will be used on another context.
On my code, The marketer have PersonName value object and a FOSUserBundle User
/**
 * Class Marketer
 * @package Elite\Model\Inquiry
 */
class Marketer
{

    private $userAccount;
    private $name;

    public function __construct(IdentityUser $userAccount, PersonName $name)
    {
        $this->userAccount = $userAccount;
        $this->name = $name;
    }
}

/**
 * The receiver of the inquiry
 * @package Elite\Model\Inquiry
 */
class Encoder
{
    public function __construct(IdentityUser $userAccount, PersonName $name)
    {
        parent::__construct($userAccount, $name);
    }

    /**
     * Make an inquiry for the inquirer
     *
     * @param Inquirer $inquirer The inquirer
     *
     * @param Marketer $marketer The marketer to be assigned to follow up
     * @param \DateTime $date The date of inquiry
     * @return Inquiry The inquiry
     */
    public function makeInquiry(Inquirer $inquirer, Marketer $marketer, \DateTime $date)
    {
        return new Inquiry($inquirer, $this->userAccount, $marketer, $date);
    }
}

How can I map the two entity on one table?
Is there a better design than what I currently have right now?
Does the Inquiry needs to have the Encoder on its constructor?
Should I instantiate the Inquiry outside the encoder? and just pass the instance of the FOSUSer to INquiry?

A: I recommend reading the books "Domain-Driven Design" of Eric Evans and "Implementing Domain-Driven Design" of Vaughn Vernon. DDD is not so much about data. So are you sure that Marketer and Encoder really belong to the same bounded contect and even aggregate especially if they are the users of the system regarding that users and authorization is normaly a seperate bounded context? Otherwise use value objects to represent the Marketer and Encoder. Use Entities only if really needed (maintaining identity if value changes). And couple them with one of the standard methods in the books to the users in the user context.
To answer your question about the one table: The thing that matches your "shared table" most closely in DDD is the "shared kernel". But it is considered a bad choice in more complex scenarios and should only be used with care. If user, marketer and encoder end up in different bounded contexts, they should be stored in different tables because every bounded context has its own data storage (at least in my understanding of DDD).


text:
Q: Validating a reset password token fails in one method, but works in another in ASP.NET Identity We're trying to use the UserManager to generate a PasswordResetToken and verifying it, before actually resetting the password.
The first method is responsible for the generation of the token, which is then sent to the user via a password reset link.
The generation of the token works fine and when validating it after, the VerifyUserTokenAsync returns true (line: //var result = await this.userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, UserManager<User>.ResetPasswordTokenPurpose, token);
The second method is for resetting the password. We're not using the UserManager.ResetPassword because our user doesn not have all the required fields.
When calling VerfiyUserTokenAsync in this method, if returns false even though the provided token is exactly the same as in the first method.
We can't wrap our heads around why it works in the first method, but fails in the second...
Any clue would be highly appreciated.
Thanks in advance
[HttpPost("generatepasswordresettoken")]
[ProducesResponseType(StatusCodes.Status201Created)]
public async Task<IActionResult> GeneratePasswordResetToken([FromBody] ResetPasswordTokenRequest resetPasswordTokenRequest)
{
    var user = await this.userService.GetAsync(resetPasswordTokenRequest.Email);
    var token = await this.userManager.GeneratePasswordResetTokenAsync(user);
    //var result = await this.userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, UserManager<User>.ResetPasswordTokenPurpose, token);

    return this.Ok(new GenerateResetPasswordTokeResponse {ResetPasswordToken = token, Email = resetPasswordTokenRequest.Email});
}

[HttpPut("resetpassword")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status500InternalServerError)]
public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequest resetPasswordRequest)
{
    var user = await this.userService.GetAsync(resetPasswordRequest.Email);
    if (await this.userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, UserManager<User>.ResetPasswordTokenPurpose, resetPasswordRequest.ResetPasswordToken)) {
        var resetPasswordDomainModel = this.resetPasswordMapper.Map(resetPasswordRequest);
        if (await this.userService.ResetPasswordAsync(resetPasswordDomainModel)) {
            return this.Ok();
        }
    }

     return this.BadRequest("Couldn't reset password");
}

A: Each SecurityToken should be valid just for one operation and this behavior of VerifyUserTokenAsync method is an advantage.
Otherwise you need to write some code to do control this behavior by yourself. In your case, you can generate new token then pass its to ResetPasswordAsync method.
    [HttpPut("resetpassword")]
    [ProducesResponseType(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status500InternalServerError)]
    public async Task<IActionResult> ResetPassword([FromBody] ResetPasswordRequest resetPasswordRequest)
    {
        var user = await this.userService.GetAsync(resetPasswordRequest.Email);
        if (await this.userManager.VerifyUserTokenAsync(user, TokenOptions.DefaultProvider, UserManager<User>.ResetPasswordTokenPurpose, resetPasswordRequest.ResetPasswordToken))
        {
            var newtoken = userManager.GeneratePasswordResetTokenAsync(user);
            resetPasswordRequest.ResetPasswordToken = newtoken;
            var resetPasswordDomainModel = this.resetPasswordMapper.Map(resetPasswordRequest);
            if (await this.userService.ResetPasswordAsync(resetPasswordDomainModel))
            {
                return this.Ok();
            }
        }

        return this.BadRequest("Couldn't reset password");
    }


text:
Q: Можно ли работать с mongodb напрямую из браузера, без использования node.js? Можно ли работать с mongodb напрямую из браузера, без использования node.js?
A: Во-первых, какой смысл тогда в БД? Что от нее остается, кроме как большего хранилища данных, которое может почистить либо слить любой, кому не лень? Во-вторых, mongodb - это база данных и она никак не требует использовать на сервере именно node.js (хотя с нодой ИМХО - "сексуальнее" всего).
Несмотря на то, что такого делать нельзя, вы можете ооочень просто написать клиентский API для возможности выполнения любых запросов, но имейте ввиду, их так же сможет выполнить любой пользователь, знающий JavaScript.


text:
Q: Polymporphism in C# - What is the point of it? I'm trying to understand the Polymorphism, but I cannot understand it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HelloWorld
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Parent Andrew = new Child();
        }

        class Parent
        {
           public int age;
           public string name;
            public virtual void message()
            {
                Console.WriteLine("I'm a parent");
            }
        }

        class Child : Parent
        {
           public string childName;
           public override void message()
           {
                Console.WriteLine("I'm a child");
           }
        }
    }
}

What's the point of creating an instance of "Parent" class and allocating it the pattern of inherited class "Child". I saw this on some tutorials, and I cannot understand why would we do that if we cannot access "Child" class variables through this instance created.
Thank you =). Hope I pointed well my problem, if not, let me know.


text:
Q: Does an NSFilePromiseProviderDelegate need to be also an NSView or NSViewController? I am going through the AppKit tutorial Supporting Drag and Drop Through File Promises. I downloaded the demo app.
I tried to extract the NSFilePromiseProviderDelegate functionality from the ImageCanvasController class (which is an NSViewController) into a separate class. (Please see before & after code snippets below.)
Before my changes, dragging an image from the app canvas out into Finder and Apple Notes worked fine. But after my changes, nothing happens when I drag into Notes, and I get this error when I drag into Finder:
2022-02-26 23:16:52.713742+0100 MemeGenerator[31536:1975798] *** CFMessagePort: dropping corrupt reply Mach message (0b000100)
Is there any undocumented protocol conformance that I need to add to the new class? Or is there some underlying logic for which NSFilePromiseProviderDelegate only works if it's also an NSView or an NSViewController? In all the guides I found online, it is always tied to a view, but I didn't find any warning that it has to be.
Note:
The reason I want to separate the promise-provider functionality from views is, this way I could provide multiple NSDraggingItem objects to beginDraggingSession. For example, when multiple items are selected, and there is a mouseDragged event on one of them, I could start a dragging session including all the selected items.
Code before
class ImageCanvasController: NSViewController, NSFilePromiseProviderDelegate, ImageCanvasDelegate, NSToolbarDelegate {

    ...

    /// Queue used for reading and writing file promises.
    private lazy var workQueue: OperationQueue = {
        let providerQueue = OperationQueue()
        providerQueue.qualityOfService = .userInitiated
        return providerQueue
    }()

    ...

    func pasteboardWriter(forImageCanvas imageCanvas: ImageCanvas) -> NSPasteboardWriting {
        let provider = NSFilePromiseProvider(fileType: kUTTypeJPEG as String, delegate: self)
        provider.userInfo = imageCanvas.snapshotItem
        return provider
    }

    // MARK: - NSFilePromiseProviderDelegate

    /// - Tag: ProvideFileName
    func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
        let droppedFileName = NSLocalizedString("DropFileTitle", comment: "")
        return droppedFileName + ".jpg"
    }

    /// - Tag: ProvideOperationQueue
    func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
        return workQueue
    }

    /// - Tag: PerformFileWriting
    func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: @escaping (Error?) -> Void) {
        do {
            if let snapshot = filePromiseProvider.userInfo as? ImageCanvas.SnapshotItem {
                try snapshot.jpegRepresentation?.write(to: url)
            } else {
                throw RuntimeError.unavailableSnapshot
            }
            completionHandler(nil)
        } catch let error {
            completionHandler(error)
        }
    }
}

Code after
class CustomFilePromiseProviderDelegate: NSObject, NSFilePromiseProviderDelegate {
    /// Queue used for reading and writing file promises.
    private lazy var workQueue: OperationQueue = {
        let providerQueue = OperationQueue()
        providerQueue.qualityOfService = .userInitiated
        return providerQueue
    }()

    /// - Tag: ProvideFileName
    func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, fileNameForType fileType: String) -> String {
        let droppedFileName = NSLocalizedString("DropFileTitle", comment: "")
        return droppedFileName + ".jpg"
    }

    /// - Tag: ProvideOperationQueue
    func operationQueue(for filePromiseProvider: NSFilePromiseProvider) -> OperationQueue {
        return workQueue
    }

    /// - Tag: PerformFileWriting
    func filePromiseProvider(_ filePromiseProvider: NSFilePromiseProvider, writePromiseTo url: URL, completionHandler: @escaping (Error?) -> Void) {
        do {
            if let snapshot = filePromiseProvider.userInfo as? ImageCanvas.SnapshotItem {
                try snapshot.jpegRepresentation?.write(to: url)
            } else {
                throw RuntimeError.unavailableSnapshot
            }
            completionHandler(nil)
        } catch let error {
            completionHandler(error)
        }
    }
}

class ImageCanvasController: NSViewController, ImageCanvasDelegate, NSToolbarDelegate {

    ...

    func pasteboardWriter(forImageCanvas imageCanvas: ImageCanvas) -> NSPasteboardWriting {
        let delegate = CustomFilePromiseProviderDelegate()
        let provider = NSFilePromiseProvider(fileType: kUTTypeJPEG as String, delegate: delegate)
        provider.userInfo = imageCanvas.snapshotItem
        return provider
    }
}

A:
Does an NSFilePromiseProviderDelegate need to be also an NSView or NSViewController?

No.
delegate is a local variable and is released at the end of pasteboardWriter(forImageCanvas:). Without a delegate the file promise provider doesn't work. Solution: keep a strong reference to the delegate.
class ImageCanvasController: NSViewController, ImageCanvasDelegate, NSToolbarDelegate {

    let delegate = CustomFilePromiseProviderDelegate()

    ...

    func pasteboardWriter(forImageCanvas imageCanvas: ImageCanvas) -> NSPasteboardWriting {
        let provider = NSFilePromiseProvider(fileType: kUTTypeJPEG as String, delegate: delegate)
        provider.userInfo = imageCanvas.snapshotItem
        return provider
    }
}


text:
Q: Hitting time of Brownian Motion combined with another Brownian Motion gives "Cauchyprocess" Let $W(t)_{t\ge 0}, B(t)_{t\geq0}$ be independent Brownian Motions on $\Bbb R$ an $\tau(a) := \inf \{ t \geq 0 : W(t) = a\}$ the first hitting time of $a\geq0$.
Now I want the distribution of
$$X(a) := B(\tau (a))$$
My attempt (EDITED):
I know the density of $\tau(a)$. It is $$\rho_{\tau(a)}(t)= \frac a {\sqrt{2 \pi t^3}} \exp\left({\frac {- a^2}{2t}}\right)$$
So further we can calculate for a suitable function $f$:
$$\Bbb E[f(X(a))] = \Bbb E [f(B(\tau (a)))] =\int_0^\infty \frac a {\sqrt{2 \pi t^3}} \exp\left({\frac {- a^2}{2t}}\right) \int_\Bbb R \frac 1 {\sqrt{2\pi t}}\exp\left( \frac {- y^2}{2t} \right) f(y) \text{d}y \text{d}t \\
= \int_\Bbb R f(y)  \int_0^\infty \frac{a}{2\pi t^2}\exp\left( \frac {-a^2  - y^2}{2t} \right) \text{d}t \text{d}y  $$
But here I don't know how to get further. So far I know it should be
$$\int_0^\infty \frac{a}{2\pi t^2}\exp\left( \frac {-a^2  - y^2}{2t} \right) \text{d}t \overset{!}{=} \frac {a}{\pi(a^2 +y^2)}$$
But I think that is not the way to do it, maybe someone has another idea for this.
EDIT: it is straight forward to show the (!)

A: Distributions are uniquely characterized by their characteristic function, and therefore it suffices to calculate the characteristic function. Using the independence of $(B_t)_{t \geq 0}$ and $\tau(a)$ we find
$$\mathbb{E}\exp(i \xi X(a)) = \int \mathbb{E}\exp(i \xi B_t) \, d\mathbb{P}_{\tau(a)}(t) = \int \exp \left(- \frac{t}{2} |\xi|^2 \right) \, d\mathbb{P}_{\tau(a)}(t).$$
(Here $\mathbb{P}_{\tau(a)}$ denotes the distribution of $\tau(a)$.) Plugging in the distribution of $\tau(a)$, we obtain
$$\begin{align*} \mathbb{E}\exp(i \xi X(a)) &= \frac{a}{\sqrt{2\pi}} \int_{(0,\infty)} \frac{1}{t^{3/2}} \exp \left(- \frac{t}{2} \xi^2- \frac{a^2}{2t} \right) \, dt \\ &= \frac{a}{\sqrt{2\pi}} e^{-|\xi| a}\int_{(0,\infty)} \frac{1}{t^{3/2}} \exp \left(- \left[\sqrt{\frac{t}{2}} |\xi|- \frac{a}{\sqrt{2t}} \right]^2 \right) \, dt. \tag{1} \end{align*}$$
If we change the variables according to $t=a^2/(|\xi|^2 s)$, i.e. $dt=-a^2/(\xi^2 s^2) ds$, we find
$$\begin{align*} \mathbb{E}\exp(i \xi X(a)) &= \frac{a}{\sqrt{2\pi}} e^{-|\xi| a} \frac{a^2}{\xi^2} \int_{(0,\infty)} \left( \frac{\xi^2 s}{a^2} \right)^{3/2} \exp \left(- \left[ \frac{a}{\sqrt{2s}} - |\xi| \sqrt{\frac{2}{s}} \right]^2 \right) \frac{ds}{s^2} \\ &= \frac{1}{\sqrt{2\pi}} e^{-|\xi| a} |\xi| \int_{(0,\infty)} \frac{1}{\sqrt{s}}  \exp \left(- \left[ \frac{a}{\sqrt{2s}} - |\xi| \sqrt{\frac{s}{2}} \right]^2 \right)\,ds. \tag{2} \end{align*}$$
Writing
$$\mathbb{E}\exp(i \xi X(a)) = \frac{1}{2} \mathbb{E}\exp(i \xi X(a)) + \frac{1}{2} \mathbb{E}\exp(i \xi X(a))$$
we find from $(1)$ and $(2)$
$$\begin{align*} \mathbb{E}\exp(i \xi X(a)) &= \exp(-|\xi| a) \frac{1}{2\sqrt{2\pi}} \int_{(0,\infty)} \left(  \frac{a}{t^{3/2}} + \frac{|\xi|}{\sqrt{t}} \right) \exp \left(- \left[\sqrt{\frac{t}{2}} |\xi|- \frac{a}{\sqrt{2t}} \right]^2 \right) \, dt. \end{align*}$$
Now we perform a further change of variables; we set $y := \sqrt{t/2} |\xi| - a/\sqrt{2t}$, i.e. $$dy = \frac{1}{2 \sqrt{2}} \left( \frac{|\xi|}{\sqrt{t}}+  \frac{a}{t^{3/2}} \right) \, dt,$$
and get
$$\begin{align*} \mathbb{E}\exp(i \xi X(a)) &= \exp(-|\xi| a) \frac{1}{\sqrt{\pi}}\int_{\mathbb{R}} \exp(-y^2) \, dy = e^{-|\xi|a}. \end{align*}$$
The right-hand side is the characteristic function of the Cauchy distribution (with parameter $a$), and this finishes the proof.

A: You made a little mistake in your expression.
You should have written
$$ \begin{split}
  \Bbb E\left[f\big(B(\tau(a))\big)\right]&=\int_0^\infty\mathrm d t\frac{a}{\sqrt{2\pi t^3}}\mathrm e^{-a^2/2t}\int_{\Bbb R}f(y)\exp\left(-\frac{y^2}{2{\color{red} t}}\right)\frac{\mathrm dy}{\sqrt{2\pi t}}\\
&=\frac{a}{2\pi}\int_{\Bbb R}f(y)\mathrm dy\int_0^\infty\exp\left(-\frac{a^2+y^2}{2t}\right)\frac{\mathrm dt}{t^2}\\
&=\int_{\Bbb R}f(y)\underbrace{\frac{a}{\pi}\frac{1}{a^2+y^2}}_{\text{Cauchy law density}}\,\mathrm dy.
\end{split} $$


text:
Q: Deallocating 2D array in C For whatever reason I am getting the following error when trying to free the 2D array I created:

Error in `./a.out': free(): invalid next size (fast): 0x0000000001759310 *** Aborted (core dumped)

I printed out the contents of the array and they are correct and I am able access all of the elements. However, I am yet to be able to free it. The error occurs when going through the freeing loop, i.e. freeing double *. Would appreciate any help.
Thanks!
Here is the code:
/*allocation*/
double **block_mat = (double **) malloc (sizeof(double *) * num_blocks);
int i;
for (i = 0; i <num_blocks; i++){
    block_mat[i] = (double *) malloc (sizeof(double) * s);
}

/*freeing*/
for (i = 0; i < num_blocks; i++){
    free(block_mat[i]);
}

free(block_mat);
EDIT:
The error was found! I under-allocated memory...So when I printed out my arrays they looked like everything was fine... I allocated arrays of sizes s, but used s^2 instead. Thank you everyone!

A: Are you sure that these pointers were all allocated with distinct mallocs?
free(my_matrix->vals);
free(my_matrix->cols);
free(my_matrix->rows);
free(my_matrix);
for (i = 0; i < num_blocks; i++){
    free(block_mat[i]);
}
free(block_mat);

If two of them are the same pointer, then you are trying to free something twice.

A: You allocate space for s doubles for each block_mat[i]. Later, you access
block_mat[i][block_index] = 0;
block_index++;

but you never check that block_index goes out of bounds, which it does.
If you write beyond the s allocated doubles, you might corrupt the internal control data for the subsequent pointer, which usually is placed before the pointer returned by malloc and which is required to be intact by free.

A: This is incorrect:
free(my_matrix);
free(my_matrix->vals);
free(my_matrix->cols);
free(my_matrix->rows);

The order should be at least like this:
free(my_matrix->vals);
free(my_matrix->cols);
free(my_matrix->rows);
free(my_matrix);

A: You have several problem that can impact allocation. The first, what if the call to strtol fails?
    s = (int)strtol(argv [3], &ptr, 10);

You should check the conversion:
#include <errno.h>
...
else {
    errno = 0;
    long tmp = strtol(argv [3], &ptr, 10);
    if ((errno == ERANGE && (tmp == LONG_MIN || tmp == LONG_MAX)) ||
        (errno != 0 && tmp == 0)) {
        perror ("strtol");
        exit (EXIT_FAILURE);
    }

    if (ptr == argv[3]) {
        fprintf (stderr, "No digits were found\n");
        exit (EXIT_FAILURE);
    }
    s = (int)tmp;
}

Next, with your allocation and free, you were on the right track, but don't cast the return of malloc. Casting the return only increases the chance of a hard to debug error. When allocating a pointer-to-pointer-to-double, you need to allocate as many pointers as needed. (num_blocks) in your case. When computing the size of the allocation, you can simply dereference the variable being allocated which again lessens the chance of error:
int i;
double **block_mat = malloc (sizeof *block_mat * num_blocks);
/* check allocation for failure */

for (i = 0; i <num_blocks; i++){
    block_mat[i] = malloc (sizeof **block_mat * s);
    /* check allocation for failure */
}

/*freeing*/
for (i = 0; i < num_blocks; i++){
    free (block_mat[i]);
}
free(block_mat);

Note: you must initialize all values in block_mat before you begin referencing the elements to prevent the deference of an unassigned value later. (e.g. double result = block_mat[i][j] * Pi;) Consider adding:
    block_mat[i] = malloc (sizeof **block_mat * s);
    /* check for failure */
    block_mat[i] = 0.0;

Note: When allocating numerical matricies, consider using calloc instead of malloc as it will initialize all values to '0' and prevent the inadvertent dereference of an unassigned valued -- which is undefined behavior. Using calloc you would have:
int i;
double **block_mat = calloc (num_blocks, sizeof *block_mat);
/* check allocation for failure */

for (i = 0; i <num_blocks; i++){
    block_mat[i] = calloc (s, sizeof **block_mat);
    /* check allocation for failure */
}

/*freeing*/
for (i = 0; i < num_blocks; i++){
    free (block_mat[i]);
}
free(block_mat);

Note: when s is greater than 1, you will alloc space for more than one double at each pointer. Noting prevents you from doing that, but you are responsible for handling the offset to each value. (e.g. result = *(block_mat[i] + j + n * sizeof **block_mat) * Pi;, where n is 0 <= n < s) If you are storing multiple doubles in each pointer, consider using a pointer-to-struct instead. E.g.:
typedef struct point {
    double x;
    double y;
    double z;
} point;


text:
Q: JPA counterpart to Hibernate IdTransferringMergeEventListener I want to switch my application from pure Hibernate to JPA 2.0. The application uses the IdTransferringMergeEventListener implemented by Spring to put back a newly generated database ID to the entity-reference if a new entity gets persisted. Therefore the hibernate "merge" event is listened to.
My question:
Is there a way to do this when using a JPA 2.0 EntityManager (we're using the Hibernate implementation of JPA)?
A testcase like this should work when using JPA:
    Entity myNewEntity = new Entity();
    entityManager.merge(myNewEntity);
    assertNotNull(myNewEntity.getId());

There is loads of already existing code so it is not an option to change code to this (which would work):
    Entity myNewEntity = new Entity();
    myNewEntity = entityManager.merge(myNewEntity);
    assertNotNull(myNewEntity.getId());

Is there anyone who can provide some tipps or hints? Any help is really appreciated.
Thanks, chris


text:
Q: HTML: Focus On Textbox When Page Loads How do you focus on a text box when page loads? I have tried the autofocus attribute with no success.
Here's my form: http://pastebin.com/xMJfQkcs

A: What browser are you using? The autofocus attribute works on major browsers and IE10+. http://jsfiddle.net/zLLSf/
<input type="text" name="name" autofocus >


text:
Q: Can't access an exported shell variable from within a script? This is all while ssh'd into an AWS EC2 Ubuntu 18 instance.
In my ~/.bashrc:
export AWS_DEFAULT_REGION="us-west-2"

In the shell:
$ echo $AWS_DEFAULT_REGION
us-west-2

But when I run this script:
#!/usr/bin/env bash

echo "starting"

echo $AWS_DEFAULT_REGION

I get this output:
starting

with an empty line below "starting".
Everything I've found on google is people who failed to export their vars, but mine is exported so I'm at a loss for what could be going wrong.
I've even tried to explicitly export the var from within the shell.


text:
Q: Unity - Resolve dependency based on generic type I have a class named DocumentRepository<T>
with constructor
DocumentDbRepository(IDocumentCollectionName collectionName)

Where IDocumentCollectionName can be
CollectionNameFromClassName<T>

or
CollectionNameFromString

And I am resolving this by
container.RegisterType(typeof(IDocumentDbRepository<ClassA>), typeof(DocumentDbRepository<ClassA>))

container.RegisterType(typeof(IDocumentDbRepository<ClassB>), typeof(DocumentDbRepository<ClassB>))

So far so good.
But now I want to resolve IDocumentCollectionName to either CollectionNameFromClassName or CollectionNameFromString depending on the Generic Type.
So if I have ClassA, I want IDocumentCollectionName to resolve to CollectionNameFromClassName<ClassA>
And if i have ClassB, I want IDocumentCollectionName to resolve to CollectionNameFromString with a string parameter value

A: According to this answer, this might work:
container.RegisterType<IDocumentCollectionName, CollectionNameFromClassName<ClassA>>("ForClassA");
container.RegisterType<IDocumentCollectionName, CollectionNameFromString>("ForClassB");

container.RegisterType<IDocumentDbRepository<ClassA>, DocumentDbRepository<ClassA>>(new InjectionConstructor(new ResolvedParameter<IDocumentCollectionName>("ForClassA")));
container.RegisterType<IDocumentDbRepository<ClassB>, DocumentDbRepository<ClassB>>(new InjectionConstructor(new ResolvedParameter<IDocumentCollectionName>("ForClassB")));

EDIT: If lisibility is your concern, I can propose to you, this:
First, you create a function to do something like your factory:
void RegisterDocumentDbRepository<TRepository, TCollection>(ContainerType container)
{
    container.RegisterType<IDocumentCollectionName, TCollection>(typeof(TRepository).Name);
    var constructor = new InjectionConstructor(new ResolvedParameter<IDocumentCollectionName>(typeof(TRepository).Name));
    container.RegisterType<IDocumentDbRepository<TRepository>, DocumentDbRepository<TRepository>>(constructor);
}

Then, you register your type like this:
RegisterDocumentDbRepository<ClassA, CollectionNameFromClassName<ClassA>>(container);
RegisterDocumentDbRepository<ClassB, CollectionNameFromString>(container);

A: I found my answer here
Unity register generic type for non generic interface
end code looks like
container.RegisterInstance<Func<Type, IDocumentCollectionName>>(type =>
{
    if (type == typeof(ClassA))
        return
            (IDocumentCollectionName)
                container.Resolve(typeof(CollectionNameFromClassName<>).MakeGenericType(type));
    else
        return (IDocumentCollectionName)
            container.Resolve(typeof(CollectionNameFromString));

});

of course this means that I had to change my
DocumentDbRepository(IDocumentCollectionName collectionName)

to
Func<Type, IDocumentCollectionName> collectionName

and resolve it as
collectionName(typeof(T))


text: Q: What are the display specs when you play a splitscreen console game? If I play a splitscreen console game which splits horizontally, what are the display specs for each half? Assuming that for non-split screen the specs are 1080p, 1920 * 1080 resolution, 60 fps, and 16:9 aspect ratio. Specifically, the game I am curious about is Call of Duty Black Ops 3 for Xbox One (I know it may run in a slightly lower resolution than advertised, just asume that the advertised resolution is correct).


text:
Q: Porque é que retorna sempre null? Criei este FIDDLE como teste.
Tenho esta li dentro de uma variável e pretendo adicionar a classe c2 a essa mesma li
var linha = '
 ' +
            '
1
' +
            '
2

'

document.getElementById('id1').addClass('c2');

O meu problema é que o document.getElementById('id1') dá-me sempre NULL e depois quando tento adicionar a classe dá-me o erro:

A: Estás a misturar elementos nativos com métodos do jQuery. O document.getElementById('id1') dá null porque no document (i.e. a página) não existe nenhum elemento com id id1. Ele existe somente dentro da string linha.
Se queres usar o addClass tens de selecionar o elemento com jQuery assim:
var linha = '
 ' +
    '
1
' +
    '
2

'
var $linha = $(linha);
$linha.addClass('c2');
$(document.body).append($linha); // ou dentro do
 que imagino que tenhas

jsFiddle: http://jsfiddle.net/9p37Lff1/
Podes criar uma div temporária para fazer mudanças dessas. Se usares métodos nativos podes usar o classList assim:
var linha = '
 ' +
    '
1
' +
    '
2

'
var temp = document.createElement('div');
temp.innerHTML = linha;
temp.querySelector('#id1').classList.add('c2');
document.body.innerHTML = temp.innerHTML;

jsFiddle: http://jsfiddle.net/9p37Lff1/1/

A: O problema é que sua variável linha não está adicionada ao document para que você possa fazer a seleção através de document.getElementById('id1'), então para resolver isso sem a utilização de jQuery, você deve adicionar a variável linha a um DOM, no caso pode ser um DOM virtual:

var linha = '
 ' +
  '
1
' +
  '
2

';

// cria dom virtual
var domVirtual = document.createElement("span");
// adicionar string html ao domVirtual, tornado-a um elemento html de fato
domVirtual.innerHTML = linha;
// seleciona elemento no dom virtual por id
var id1 = domVirtual.querySelector("#id1");
// adiciona class ao elemento
id1.classList.add("c2");

console.log(id1.className)

// agora aqui sua variavel id1, já está com o elemento pronto para ser utilizado.

Exemplo jsFiddle.
Outro problema em seu código é que não há o método addClass na interface Element, onde você pode utilizar para essa finalidade o método classList (que é readonly), utilizando então o método add() do classList, sendo representado por essa parte do código apresentado anteriormente:
// adiciona class ao elemento
id1.classList.add("c2");

A: Complementando a resposta do @Sergio, não precisa selecionar por id pois quando você passa uma string com html para o jquery, como está a utilizar, o mesmo mantém como seleção todos os elementos root (no caso, apenas a li que você deseja).
Caso você tenha mais li's na string, pode utilizar o método filter, ou ainda, se o que você quer está em elementos de nível mais baixo, pode utilizar o find.
var $linha = $("
li a ser selecionada
" +
               "
li não selecionada
");
$linha.filter("#id1").addClass("c2");

var $linha = $("
" +
                   "
li a ser selecionada
" +
                   "
li não selecionada
" +
               "
");
$linha.find("#id1").addClass("c2");