text:
Q: Collision detection in grid map? There is a grid map (tile map). Among all the tiles, some are free (empty) and some are obstacles.
Now if I randomly pick to empty tiles (tile A and tile B) and draw a line segment across them.
What is the fastest algorithm to tell whether this line segment is collision free to any obstacles or not? (In the figure below: Red tiles are obstacles, Line_2 is collision free, Line_1 is not)
Currently, what I am doing is to do a voxel traversal from A to B and check the traversed tiles whether it contains an obstacle or not?

But is there better solution?

A: I believe, the speed of algorithm depends of the size of the field and the amount of obstacles. Your way is excellent if the field is full of obstacles.
Another way is finding the points of intersection of the ray and each side of the tile.

I think this way is excellent if you have a few tiles and a lot of free space.
UPD: This method should be optimized by exclusion calculations for the "back sides" of tiles for all the set. It will decrease amount of calculations and speed up the routine.
Finally, I believe, you can use both algorithms in your code. You can select a method by approximation the "density" of the map.


text:
Q: routing algorithm different to Dijkstra-concept what kind of routing algorithms exists that are different to different to Dijkstra-concept?
Dijkstra (and A*,D*, bellman forge etc.) use this concept:
Get the best Node from known Nodes, expand this and save the results to the known Nodes.
Are there any concepts that are fundamental different?

A: Bellman-Ford is fundamentally different. It uses dynamic programing instead of the Dijkstra greedy approach and works for graphs with negative weight edges.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Calling Webservice in iPhone application? I am using soap webservice.
In that i am calling one webmethod. Here if i call  from one part of my code is working fine and calling service successfully and retriving data successfully.
But if i calling same method from another part of code of same class is not responding and not getting any data from service. Why is going like that can any one help me please.
Thanks in advance
In detail.m
-(void) downloadAndParse:(NSMutableURLRequest *)sentReq  {

    conn =  [[NSURLConnection alloc] initWithRequest:sentReq delegate:self];

    if (conn) {
        webData = [[NSMutableData data] retain];
    }
}

-(void)fullBarcodeSearch:(NSString *)code {

    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    URLRequest *r  = [[URLRequest alloc] init];

    NSMutableURLRequest *req = [r fullBarcodeSearch:code];
    [r release];
    [self downloadAndParse:req];

}

In URLRequest.m
-(NSMutableURLRequest *) addHeaderToSoapXML:(NSString *) soapMsg {

    NSURL *url = [NSURL URLWithString:str];

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d",[soapMsg length]];
    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"content-type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody:[soapMsg dataUsingEncoding:NSUTF8StringEncoding]];
    return req;
}

if service not called then i am getting error like this
*oid _WebThreadLockFromAnyThread(bool), 0x6958130: Obtaining the web lock from a thread other than the main thread or the web thread. UIKit should not be called from a secondary thread.*
Please any one help me
Thanks in advance

A: You need an NSURLConnection to execute the NSURLRequest. Lookup the Apple Docs on the class.
Something like:
[urlConnection sendSynchronousRequest:urlRequest returningResponse: &urlResponse error:&error]


text:
Q: New icons in iOS 7 I was trying to update my iOS app and I received some warnings about three missing icons.

Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format.
Missing recommended icon file - The bundle does not contain an app icon for iPad of exactly '76x76' pixels, in .png format.
Missing recommended icon file - The bundle does not contain an app icon for iPad of exactly '152x152' pixels, in .png format.

I don't know if I have to add these icons too and where to add them or if a have to replace them for the ones that the app already has (57-114 for iPhone and 72-144 for iPad).

A: Check the new App icon sizes:

Reference is here.


text:
Q: client app (steroids, ionic, cordova) using Breeze cannot connect to WebApi OData for metadata. Invalid HTTP status code 405 I create a WebApi 2.2 OData v1-3 which uses Code First. Here is my ODataConfig
public static class ODataConfig
{
    public static void Register(HttpConfiguration config)
    {
        #region Normal way to build EDM model the Microsoft way
        ODataModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<Gear>("Gears");
        ...
        #endregion

        // enable CORS
        var cors = new EnableCorsAttribute("*", "*", "*", "DataServiceVersion, MaxDataServiceVersion");
        config.EnableCors(cors);

        config.Routes.MapODataServiceRoute(
            routeName: "odata",
            routePrefix: "odata",
            model: builder.GetEdmModel());
    }
}

In my Global.asax.cs I call it in the Application_Start()
GlobalConfiguration.Configure(ODataConfig.Register);

My controller is a ODataController
public class GearsController : ODataController
{...}

I can build the project and try those with no problem
localhost:51131/OData/Gears

{
    "odata.metadata":"http://localhost:51131/odata/$metadata#Gears","value":[
      {
        "Title":"Burton 729","Description":"Burton 720","Size":"12","Defects":"No defects","PricePerDay":12.0,"PricePerWeek":50.0,"AuthorizedAmount":400.0,"LikeCount":1,"ViewCount":25,"BootSize":10,"Banner":null,"OwnerID":3,"ID":3
      },{
        "Title":"Burton 360","Description":"Burton 360","Size":"10","Defects":"No defects","PricePerDay":12.0,"PricePerWeek":60.0,"AuthorizedAmount":450.0,"LikeCount":1,"ViewCount":25,"BootSize":11,"Banner":null,"OwnerID":1,"ID":4
      }
    ]
  }

localhost:51131/OData/$metadata

Then I have a client which bower install the "angular", "breezejs", "datajs". I create a breezeODataService
(function () {
'use strict';

angular.module('tahoeApp.services.data').factory('breezeODataService', breezeODataService);
breezeODataService.inject = ['breeze', 'model'];
function breezeODataService(breeze, model) {
    configureBreeze();

    var serviceName = 'http://localhost:51131/odata';

    var metadataStore = new breeze.MetadataStore();
    var factory = {
        newManager: newManager,
        serviceName: serviceName,
        metadataStore: metadataStore
    };

    return factory;

    function configureBreeze() {
        // use Web API OData to query and save
        breeze.config.initializeAdapterInstance('dataService', 'webApiOData', true);

        // convert between server-side PascalCase and client-side camelCase
        breeze.NamingConvention.camelCase.setAsDefault();
    }

    function newManager() {
        var mgr = new breeze.EntityManager(serviceName);
        return mgr;
    }
}})();

Then I try to get all the Gear data from GearsController like this
function getAll() {
        var self = this;
        debugger;
        return EntityQuery.from('Gears')
            .using(self.manager).execute()
            .then(querySucceeded).catch(queryFailed);

        function querySucceeded(data) {
            debugger;
            return data.results;
        }

        function queryFailed(error) {
            throw error;
        }
    }

But it always returns to the

queryFailed

with the message:

XMLHttpRequest cannot load [http:]localhost:51131/odata/$metadata. Invalid HTTP status code 405
  ionic.bundle.js:17822 Error: Metadata query failed for: [http]localhost:51131/odata/$metadata;
      at createError (breeze.debug.js:16436)
      at breeze.debug.js:16214
      at XMLHttpRequest.r.defaultHttpClient.request.f.onreadystatechange (datajs-1.1.2.min.js:13)


text:
Q: How should I update database and RecyclerView in Kotlin after every midnight? I would like to make a simple Habit Tracker app in Kotlin.
I already have a main database where the app stores the habits with dates, and a 'Daily View' where the user can see his habits and check/uncheck them.
My main problem is that I don't know how add new habits with new dates and unchecked checkboxes to the database after every midnight.
Here is the code I wrote:
HabitItem.kt
@Entity(tableName = "habititem")
data class HabitItem(
    @ColumnInfo(name = "habitId") @PrimaryKey(autoGenerate = true) var id: Long? = null,
    @ColumnInfo(name = "name") var name: String,
    @ColumnInfo(name = "description") var description: String,
    @ColumnInfo(name = "date") var date: String,
    @ColumnInfo(name = "isDone") var isDone: Boolean
) { }

HabitListDatabase.kt
@Database(entities = [HabitItem::class], version = 1)
abstract class HabitListDatabase : RoomDatabase() {
    abstract fun habitItemDao(): HabitDao

    companion object {
        fun getDatabase(applicationContext: Context): HabitListDatabase {
            return Room.databaseBuilder(
                applicationContext,
                HabitListDatabase::class.java,
                "habit-list"
            ).build();
        }
    }
}

HabitDao.kt
@Dao
interface HabitDao {
    @Query("SELECT * FROM habititem")
    fun getAll(): List<HabitItem>

    @Insert
    fun insert(shoppingItems: HabitItem): Long

    @Update
    fun update(habitItem: HabitItem)

    @Delete
    fun deleteItem(habitItem: HabitItem)
}

HabitAdapter.kt
class HabitAdapter(private val listener: HabitItemClickListener) :
    RecyclerView.Adapter<HabitAdapter.HabitViewHolder>(){

    private val items = mutableListOf<HabitItem>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = HabitViewHolder(
        ItemHabitListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    )

    override fun getItemCount(): Int = items.size

    interface HabitItemClickListener {
        fun onItemChanged(item: HabitItem)
        fun itemIsDeleted(item: HabitItem)
    }

    inner class HabitViewHolder(val binding: ItemHabitListBinding) : RecyclerView.ViewHolder(binding.root)

    override fun onBindViewHolder(holder: HabitViewHolder, position: Int) {
        val habitItem = items[position]

        holder.binding.tvName.text = habitItem.name
        holder.binding.tvDescription.text = habitItem.description
        holder.binding.cbIsDone.isChecked = habitItem.isDone

        holder.binding.cbIsDone.setOnCheckedChangeListener{ buttonView, isChecked ->
            habitItem.isDone = isChecked
            listener.onItemChanged(habitItem)
        }

        holder.binding.ibRemove.setOnClickListener {
            deleteItem(habitItem)
            listener.itemIsDeleted(habitItem)
        }
    }

    fun deleteItem(item: HabitItem) {
        items.remove(item)
        notifyDataSetChanged()
    }

    fun addItem(item: HabitItem) {
        items.add(item)
        notifyItemInserted(items.size - 1)
    }

    fun update(habitItems: List<HabitItem>) {
        items.clear()
        items.addAll(habitItems)
        notifyDataSetChanged()
    }
}


text:
Q: serializing array of objects I'm populating an array nodevalues with objects. It looks like this:
nodevalues.push({id: this.id, left: left, right: right});
This line is inside a $.each() iterator which iterates over some li nodes and also calculates the left and right values.
So I have an array with several objects who all look the same:
Is it possible to serialize this array to an url string for database storage using jQuery.post()?
Calling $(nodevalues).serialize() returns nothing and $.param(nodevalues) returns undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined&undefined=undefined...

A: jQuery.param() might do what you want
var dataString = jQuery.param(nodevalues);

It seems that param only works on objects, not arrays.
If you wrap your array in an object it works fine:
var nodevalues = [];

nodevalues.push({id: "node1", left: 1, right: 20});
nodevalues.push({id: "node2", left: 2, right: 10});
nodevalues.push({id: "node3", left: 3, right: 30});
nodevalues.push({id: "node4", left: 4, right: 40});

var data = { data: nodevalues };

alert($.param(data));

http://jsfiddle.net/4NELt/

A: You could use the stringify function from the JSON library.

A: you can supply the data as second argument to jquery.post()
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] );

jquery will serialize it for you.


text:
Q: Getting an error Request entity is too large I am redirecting from one page to another by using this command.
Response.Redirect("~/Viewer/ViewerTest.aspx");

Sometimes, I am redirected to this page and sometimes, I am not. Actually very rarely, i am redirected to this page. If I am not redirected, I get an error

The page was not displayed because the request entity is too large

I tried to play around with this command by putting actual project name instead of tilde, but again sometimes it worked sometimes, it does not.
Response.Redirect("~/Viewer/ViewerTest.aspx");

Along with the above command, I am passing a query string with it, the query string value is very small, it is Id=<the calculated value> which is integer value not more than 100.
Also, this error is not coming on development computer, only on my production computer. My dev computer works fine. The production computer has Windows Server 2008 and my dev computer has XP. The Internet Explorer version is 7.0
Any help will be greatly appreciated.
Thanks.

A: Sometimes it does and sometimes doesn't?
Request entity body becomes large

*

*When you upload a large file from your web page

*When you submit a web page of large content
Setting uploadReadAheadSize in applicationHost.config file on IIS7.5 would resolve your issue in both cases. You may modify this value directly in applicationhost.config or use this command:
appcmd.exe set config -section:system.webserver/serverruntime/uploadreadaheadsize: 1048576 /commit:apphost


text:
Q: Multiline html variables in webpy I have a snippet in template like this:
$ html = """

    Адрес:
    123456,
    Москва,
    Красная площадь,
    д.1,
    стр.1,
    офис 12

"""
$:htmlLoop(entry, 'address', html)

When I try to render it I get traceback:
extend_([u'
"""\n'])

                           ^
SyntaxError: unexpected character after line continuation character

And it doesn't depend on if I breal lines with \ or """.

A: web.py doesn't support triple-quoted strings. You can accomplish what you're trying to do like this:

$def html():

        Адрес:
        123456,
        Москва,
        Красная площадь,
        д.1,
        стр.1,
        офис 12

$:htmlLoop(entry, 'address', html())


text:
Q: Generating the coordinate ring of the Lubin-Tate formal group Let $K$ be a $p$-adic local field with uniformizer $\pi \in \mathcal{O}_{K}$ and residue field $k = \mathcal{O}_{K}/\pi$. Let $G$ be a Lubin-Tate formal $\mathcal{O}_{K}$-module and $G_{0}$ its reduction to $k$.
Let $G_{0}[\pi]$ denote the $\pi$-torsion subgroup of $G_{0}$, this is a finite group scheme over $k$. The action of $\mathcal{O}_{K}$ on $G_{0}$ yields an action of the multiplicative monoid $\Gamma = (k, \cdot)$ on $G_{0}[\pi]$ and hence on its coordinate ring $\mathcal{O}_{G_{0}[\pi]}$.
Question: Does there always exist an element $g \in \mathcal{O}_{G_{0}[\pi]}$ which generates the coordinate ring as a module over the monoid ring $k[\Gamma]$? How to find such an element?
Example: Suppose that $K = \mathbb{Q}_{p}$, $\pi = p$ and $G = \mathbb{G}^{\wedge}_{m}$ the formal multiplicative group, so that
$\mathcal{O}_{G[p]} \simeq \mathbb{F}_{p}[x]/((1+x)^{p}-1)$.
Then an element $[\gamma] \in \Gamma = (\mathbb{Z}/p, \cdot)$ acts on $g = x+1$ via
$[\gamma]g = [\gamma](x)+[\gamma](1) = (x+1)^{\gamma}-1+1 = (x+1)^{\gamma}$
and hence the translates of $g$ along $0, \cdots, p-1 \in \mathbb{F}_{p}$ are of the form
$(x+1)^{0}, (x+1)^{1}, \cdots, (x+1)^{p-1}$
This is a $\mathbb{F}_{p}$-basis of $\mathcal{O}_{G_{0}[\pi]}$, so $g = x+1$ gives an element which generates the whole coordinate ring as needed.
Some thoughts: 1) In the case of $\mathbb{G}_{m}^{\wedge}$, where $\mathbb{G}_{m}[p] = \mu_{p}$, another way to find an element $g$ is to notice that Cartier duality gives an isomorphism
$\mathcal{O}_{\mu_{p}} \simeq \mathcal{O}_{\mathbb{Z}/p}^{*} \simeq Fun(\mathbb{Z}/p, \mathbb{F}_{p})^{*} \simeq \mathbb{F}_{p}[\mathbb{Z}/p]$,
(where $*$ denotes the dual vector space) so that the coordinate ring is just the regular representation of the multiplicative monoid $\Gamma = \mathbb{Z}/p$ and hence must be generated by a single element.

*Also in the case of $\mathbb{G}_{m}^{\wedge}$, the invariant differential is given by $\omega(x) dx = \frac{1}{1+x} dx$. So perhaps it is possible to relate a generating element $g$ to invariant differentials?

*We have verified that such an element also exists when $G_{0}$ is the Honda formal group law of height 2 over $\mathbb{F}_{4} \simeq W(\mathbb{F}_{4})/p$, and can be taken to be
$g = 1 + x + x^{2} + x^{3} \in \mathcal{O}_{G_{0}[p]} \simeq \mathbb{F}_{4}[x]/(x^{4})$

A: I'll assume that $\pi=p$; I guess that the general case is the same but I have not checked.  We now have $k=\mathbb{F}_{p^n}$ and $\mathcal{O}_K=W\mathbb{F}_{p^n}$.  The group of roots of unity in $W\mathbb{F}_{p^n}$ is cyclic of order $p^n-1$, with generator $\omega$ say, and maps by an isomorphism to $\mathbb{F}_{p^n}^\times$. Put $f(x)=px+x^{p^n}$.  Lubin-Tate theory then says that there is a unique formal group law $F$ with $f(F(x,y))=F(f(x),f(y))$ and that this has $[p](x)=f(x)$ and $[\omega^i](x)=\omega^ix$.  The ring $R=\mathcal{O}_{G_0[\pi]}$ is just $W\mathbb{F}_{p^n}[[x]]/f(x)$, which has basis $B=\{x^i:0\leq i<p^n\}$ over $W\mathbb{F}_{p^n}$.  Put $a=1+x+\dotsb+x^{p^n-1}\in R$.  I claim that this is a generator of the required type.  More explicitly, let $b$ be the image of $a$ under the substitution $x\mapsto [0](x)=0$ i.e. $b=1$, and let $c_i$ be the image of $a$ under the substitution $x\mapsto[\omega^i](x)=\omega^ix$.  The claim is then that the list $b,c_0,c_1,\dotsc,c_{p^n-2}$ is a basis for $R$ over $W\mathbb{F}_{p^n}$.  If we write this list in terms of the monomial basis, we get a matrix $M$ of shape $p^n\times p^n$, which we must prove to be invertible.  The top row (corresponding to $b$) is just $(1,0,0,\dotsc,0)$, and the bottom right block of size $(p^n-1)\times(p^n-1)$ is the Vandermonde matrix with entries $\omega^{ij}$.  The Vandermonde determinant formula shows that this is invertible.


text:
Q: Selecting a background style using javascript - how to fix a simple syntax error? I want to just change the background when clicking the button. However, I cannot get the variable change to fetch the background of div test2 and store it as a variable. I know this because alerting the value of test2 shows undefined.
I know this seems like a simple fix but I cannot actually find a solution. Is this just a simple syntax error or am I missing something?
An explanation of why this happens would be much appreciated, thanks.

var el = document.getElementById('test');

function changeBG() {
  var change = document.getElementById('test2').background;

  el.style.background = change;
}
#test {
  background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
    width: 200px;
  height: 200px;
  background-size: cover;
  background-position: center;
}

#test2 {
  background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
}

<button onclick="changeBG();">hi</button>

A: If all you're looking to do is change style properties, you can simply toggle classes. Its totally unnecessary to create variables to do this unless you're just trying to learn something.

var el = document.getElementById('test');

function changeBG() {
    el.classList.toggle('test1');
    el.classList.toggle('test2');
}
#test {
  width: 200px;
  height: 200px;
  background-size: cover;
  background-position: center;
}

.test1 {
  background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
}

.test2 {
  background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
}

<button onclick="changeBG();">change background</button>

A: If you are looking for an old-school solution.

function changeBG() {
var el = document.getElementById('test');
var value = null;
for (let i = 0; i < document.styleSheets.length; i++) {
    const mysheet = document.styleSheets[i];
    const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
    if(myrules){
      for (let j = 0; j < myrules.length; j++) {
        if (myrules[j].selectorText &&
            myrules[j].selectorText.toLowerCase() === '#test2')     {
          value =  myrules[j].style['background'];
        }
      }
    }
  }
  if(value){
   el.style.background = value;
  }else{
  alert("test2 not found");
  }
}
#test {
  background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
    width: 200px;
  height: 200px;
  background-size: cover;
  background-position: center;
}

#test2 {
  background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
  width: 200px;
  height: 200px;
  background-size: cover;
  background-position: center;
}

 if you are looking for an old-school solution

<button onclick="javascript:changeBG();">hi</button>

A: There are a couple reasons for the error/undefined variable. First, there isn't an element with the id 'test2' in your html. You have only assigned css style to the id 'test2'. There is only a div with the id 'test'. The other problem is HTML elements do not have the property 'background'. To change the background you would need to use the 'style' property as in document.getElementById('test2').style.background = "url(...)";
There are several ways to resolve this, below is one approach using classes.

*

*Remove the background attribute from the div id and create two
classes, background and background2.

*In the html, add the background to the test div as the default
class (background image).

*Use the toggle() method to alternate assignment of the class to the
div.

Since the original class background was already assigned it will be removed and background2 is added. If you are only trying to change the background once, then you can just simply reassign the class (see commented lines).
toggle
style property
Note: The reason you can't keep the background attribute as part of the original div's id css and add the class with the new background is because the id takes precedent and will override any class attributes with the same name unless !important is added to the end of the class attribute value (background: url(..) !important;) though that method should be avoided if possible. Also, The classList property is not supported in Internet Explorer 9 if that matters.

var el = document.getElementById('test');

function changeBG() {
    //to change the background once
    //el.className = "background2";
    el.classList.toggle('background');
    el.classList.toggle('background2');
}
#test {
    width: 200px;
    height: 200px;
    background-size: cover;
    background-position: center;
}

.background{
    background: url('http://i.dailymail.co.uk/i/pix/2017/08/15/19/434758D400000578-4793442-image-a-5_1502822599189.jpg');
}

.background2 {
    background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/4/44/Lioness_and_cub.jpg/240px-Lioness_and_cub.jpg');
 }

<button onclick="changeBG();">hi</button>


text:
Q: Float:left not working Can some one please help me on this..
I am using float:left for id =row1 but why doesnt it get alinged.
There are two columns of data using div for each list, both list should be alinged to left, not below one another.
http://jsfiddle.net/c6242/1878/

Sr No:

Entry Date:

Name

Phone No:

Email ID:

MRF Code:

Location:

Total Exp:

Last Organisation:

Current CTC:

Notice Period:

Source:

Sr No1:

Entry Date1:

Name1

Phone No1:

Email ID1:

MRF Code1:

Location1:

Total Exp1:

Last Organisation1:

Current CTC1:

Notice Period1:

Source1:

Any help appreciated..

A: This is by no means the best way of doing what you're trying to achieve here - you're better off looking at tables rather than divs. But if you're really set on keeping this sort of structure, you need a wrapper div round each column, with the display set to inline-block.
http://jsfiddle.net/c6242/1880/

Sr No:

Entry Date:

Name

Phone No:

Email ID:

MRF Code:

Location:

Total Exp:

Last Organisation:

Current CTC:

Notice Period:

Source:

Sr No1:

Entry Date1:

Name1

Phone No1:

Email ID1:

MRF Code1:

Location1:

Total Exp1:

Last Organisation1:

Current CTC1:

Notice Period1:

Source1:


text:
Q: D3 adding unwanted extra line to my line chart I'm following this example on graphing multiple line charts, and for some reason it's looping through my data one too many times when it organizes the data such that I have a line graphing at y=0. (When I console log the populations variable, there is one too many objects in the array).
The data lives in this google sheet: https://docs.google.com/spreadsheets/d/1o9HowBfwUmzzVPBB-LGCKxIp-tWVljKsQP7UO59Y-G8/edit?usp=drive_web
Any suggestions for fixing this?

value

A: For whatever reason, d3.csv is adding an empty field when loading the google spreadsheet, creating an empty object pair:
{"": ""}

You can remove it from data or from populations, as I did:
var populations = populations.filter(function(d){
    return d.name != "";
});

Here is the fiddle: https://jsfiddle.net/mw9hhbjx/


text:
Q: Could not initialize Tesseract API with language=eng when I use the tess-two:6.1.1, I got below error
Tesseract(native): Could not initialize Tesseract API with language=eng!
ActivityThread: Performing resume of ActivityRecord{dc1c46c token=android.os.BinderProxy@ce1ba35 {xxx.xxxx.xxxxx/xxx.xxxx.xxxxx.MainActivity}}
D/skia: jpeg_decoder mode 1, colorType 4, w 1280, h 1280, sample 1, bsLength 0!!
I/System: FinalizerDaemon: finalize objects = 1
D/skia: jpeg_decoder finish successfully, L:1934!!!
A/libc: Fatal signal 11 (SIGSEGV), code 1, fault addr 0xc in tid 22351 (ia.testproguard)

I use this lib for gradle in android studio
compile 'com.rmtheis:tess-two:6.1.1'

I create the name "tessdata" file in root of sdcard and create emtry txt in tessdata named "eng.traineddata"
below is my code
int permissionCheck =
    ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

if (permissionCheck == -1) {
  ActivityCompat.requestPermissions(this,
      new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE }, 101);
}

baseApi = new TessBaseAPI();
custom.traineddata
baseApi.init(SD_PATH, "eng");
baseApi.setPageSegMode(TessBaseAPI.PageSegMode.PSM_AUTO);
baseApi.setImage(new File("sdcard/img.jpg"));
final String result = baseApi.getUTF8Text();
//这里,你可以把result的值赋值给你的TextView
baseApi.end();
((TextView) findViewById(R.id.test)).setText(result);

have someone know where I make mistake?


text:
Q: How to edit/remove items from a CCMenu? I have a CCMenu that contains CCMenuItemSprite and CCMenuItemLabel.
This menu is added to my layer as follows:
[self addChild:itemsMenu];
The menu is always visible to the user and contains objects that can be used by the user himself during the game. For instance, powerups that have limited life. When the player uses the objects, it must be removed from the menu.
Is there a way to delete only a single object in the CCMenu? Or do I have to recreate the full menu?
In my current implementation, I delete menu when the user finishes the number of uses associated to the CCMenuItemSprite with:
[self removeChild:itemsMenu cleanup:YES];
[self removeChild:itemsCountMenu cleanup:YES];

Thanks in advance for the help.


text:
Q: How to run shell command on Android device? I try to run shell command on android app by using Runtime class and ndk system/exec functions.
First, i use Runtime class that was guided by other user.
execute shell command from android
like this : Runtime.getRuntime().exec("/data/local/tmp/test.sh"); (i double checked file permission it was 777)
but following error happended when i run upper command.
try {
        Process process = Runtime.getRuntime().exec("/data/local/tmp/test.sh");
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
        int read;
        char[] buffer = new char[4096];
        StringBuffer output = new StringBuffer();
        while ((read = reader.read(buffer)) > 0) {
            output.append(buffer, 0, read);
        }
        reader.close();
        process.waitFor();
        return output.toString();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }

error
at com.sec.sq.myapp.apis.test.tasks.test.MyTester.exec(MyTester.java:47)
    at com.sec.sq.myapp.apis.test.tasks.test.MyTester.run(MyTester.java:29)
    at com.sec.sq.myapp.apis.manager.ThreadManager.doTask(ThreadManager.java:108)
    at com.sec.sq.myapp.apis.manager.ThreadManager.doTest(ThreadManager.java:81)
    at com.sec.sq.myapp.apis.manager.ThreadManager.run(ThreadManager.java:118)
 Caused by: java.io.IOException: error=13, Permission denied

Second, i tried native-ndk system/exec functions but it's also not working.

*

*execl("/system/bin/sh", "/data/local/tmp/test.sh", NULL);

: app crashed, and can see permission denied error=13.

system("/system/bin/sh /data/local/tmp/test.sh");

: noting happended and shell not run.
Can somebody help me to find a way how to run shell command on Android app?

A: You have problem in reading that file.Script is fine. Can you try using this:
chmod u+x /data/local/tmp/test.sh

You can also go through this this link.


text:
Q: Find highest number from a group of numbers in a div I have a set of numbers like this in a div:
1,2,3,4,5,6,7,8,9,10

How can I find the highest number from that group and display it?

A:

//read content of div
var list = document.getElementById("numbers").innerText;
//split it into an array of numbers
list = list.split(",");
//get the biggest element
var max = Math.max.apply(null, list);
//ta-daaaa
document.write("The max is: " + max);

1,2,3,4,5,6,131,23,99,8,15

That ought to do it.

A: You could try something like this:

// get the numbers that are contained in your div
var numbers = document.getElementById("numbers").innerHTML;

// split the string you have read and create an array of numbers
var array = numbers.split(',').map(function(number){ return parseFloat(number)});

// sort that array
array = array.sort(function(a,b){ return b-a;});

   // return the first element, which would be the highest.
alert("The greatest number is "+array[0]);

1,2,3,4,5,6,7,8,9,10,105.20,110.85


text:
Q: Local asp.net restart with Oauth--provider logged in but session lost I'm developing a dropbox asp.net application, and it's working at least in localhost mode. But I'm facing a problem that I hope is only during localhost testing and won't (CAN NOT) occur in production. It's a bit difficult to explain so I will describe it in steps.
1) The browser is not running and I start the "logged in membership target page" in Debugger. It asks dropbox for login and permission. At this time, in my Oauth derived class, I store my drop box object with access token and secret in a session variable.
2) In my actual "logged in" page, I extract the object from the session and start using dropbox and it works fine.
3) Now suppose I stop debugging from Visual Studio 2012. Make some modifications to the code. Now I start again. This time the browser is already logged in to dropbox and the target page is displayed logged in. I see no "Allow" prompt from dropbox. But there is no session variable now to extract my drop box object because this is a new session. But for dropbox it is the already logged in session.
I want to confirm that this situation can only occur during localhost running and can not occur in real production app because it will always go from a web site in the browser which will have its own session. Or can it occur? What is the solution in that case.
Another doubt is, why doesn't dropbox ask for Allow prompt next time if the browser is open but the app is starting a new session. It must be getting the same access token and secret from somewhere. From where?

A: I think I found a workable solution. If I find that the session has been lost, I execute the following code and it logs off the user. Even if the situation might occur only in my local testing, this takes care of it.
                FormsAuthentication.SignOut();
                Response.Redirect("/");
                return;


text:
Q: Using DataReader in Dapper with Oracle How do I get values read values line a DataReader to read values of fields returned by multi in the following code to set the values in the Class
OracleRefCursor m_Cursor=null;
Dapper.SqlMapper.GridReader multi =null;

using (m_Conn = new OracleConnection(m_ConnectionString))
{
     try
     {
          m_Conn.Open();
          String m_LastName = "S" + "%";
          String m_Id = "";
          String m_EmpId = "";

          var p = new OracleDynamicParameters();

          p.Add(":p_LastName", m_LastName);
          p.Add(":p_Id", m_Id);
          p.Add(":p_EmpId", m_EmpId);
          p.Add( ":p_Cursor1", dbType: OracleDbType.RefCursor, direction: ParameterDirection.Output );

          using (multi = m_Conn.QueryMultiple(m_ProcedureName, param: p, commandType: CommandType.StoredProcedure))
          {

          }
    }
    catch (Exception ex)
    {
           String m_Error = ex.ToString();
    }

}//end of using statement

A: From Dapper docs:
var sql =
@"
select * from Customers where CustomerId = @id
select * from Orders where CustomerId = @id
select * from Returns where CustomerId = @id";

using (var multi = connection.QueryMultiple(sql, new {id=selectedId}))
{
   var customer = multi.Read<Customer>().Single();
   var orders = multi.Read<Order>().ToList();
   var returns = multi.Read<Return>().ToList();
   ...
}


text:
Q: Finding all continuous functions such that $f^2(x + y) − f^2(x − y) = 4f(x)f(y)$ I've been working on the following homework problem:

Find all continuous functions $f : \mathbb{R} → [0,∞)$ such that $f^2(x + y) − f^2(x − y) = 4f(x)f(y)$ for all real numbers $x, y$.

The first problem I have is I am not sure what is meant by "finding all continuous functions".  Can someone show me what the ending statement should look like?
Secondly, I'm not sure what to do with the relations I've derived. The most helpful are:
$f(0) = 0$
$f(x) = f(-x)$
$f(2x) = 2f(x)$
I also know that:
$f(2) = 2f(1)$
$f(3) = \frac{3}{2}f(2)$
$f(4) = 2f(2) = 4f(1)$
This leads me to believe that $\frac{f(a)}{f(b)} = \frac{a}{b}$, but I don't know (a) if this is helpful and (b) how to prove it.
Can someone clarify what exactly the object is, and point me towards the next step?

A: The condition $f(x)\geq 0$ seems to kill all non-trivial possibilities: since $f(0)=0$ we let $y=-x:$
$$-f^2(2x)=4f(x)f(-x)$$
However $f(x)\geq 0$, so $f(x)=0$. Are you absolutely sure of the $\mathbb{R}\to [0,\infty)$ bit?

A: One thing that helps is to find useful values.  If you set $y=0$ you find $f(0)=0$.  Then if $x=y$ you get  $f^2(2x)=4f^2(x)$


text:
Q: converting latin to utf8mb4 causes questionmarks
*

*The original format of the data is unknown

*The new table is in utf8mb4_general_ci
If I do CONVERT(BINARY CONVERT(column USING latin1) USING UTF8) as mentioned here - it fixes all text, but converts something like: © in the original column to ? in the new column.
If it helps to determine what original encoding it was in, the original text renders as e.g. KotaÄići and converts to Kotačići.
Is there a way to both preserve special characters and restore correct utf8 text format?

As requested in the comments an example via hex:
HEX(col):
C398C2A3C398C2BAC399E280A0C399C5A0C398C2A920C398C2B3C399E280A620C398C2A7C399E2809EC399E2809EC399E280A1

CONVERT(BINARY CONVERT(col USING latin1) USING UTF8):
أغنية سم الله

Just raw:
أغنية سم الله

The dump-file starts with:
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

Tables get created with: ENGINE=InnoDB DEFAULT CHARSET=utf8mb4

A: Ah, I was afraid of that.  That hex string is the "double encoding" of  أغنية سم الله Does that look about right?
This is the expression to 'fix' it:  CONVERT(BINARY(CONVERT(CONVERT(UNHEX('C398C2A3C398C2BAC399E280A0C399C5A0C398C2A920C398C2B3C399E280A620C398C2A7C399E2809EC399E2809EC399E280A1') USING utf8mb4) USING latin1)) USING utf8mb4)
This discusses how it probably came about.  You need to fix your code and fix the data:  https://stackoverflow.com/questions/38363566/trouble-with-utf8-characters-what-i-see-is-not-what-i-stored  (Look for "double encod")
(utf8 and utf8mb4 work equally well for Arabic.)
That short conversion you found needs to (sort of) be repeated to fix "double" encoding.
Further research
It is OK to be a mixture of Arabic and other languages in a utf8 or utf8mb4 column. It is not ok to have double-encoding, especially if some cells are correctly encoded. Somewhere the Arabic text was encoded an extra time, but the copyright symbol was not. Did they come from different sources? Maybe the problem came before this database we are looking at?
That is, dig into the client(s) you are using and dump the hex of text that is about to be INSERTed. Arabic should be two hex bytes: Dxyy; copyright (and many other popular symbols) should be Cxyy.
Fixing
If you find that some rows have double-encoded Arabic (or whatever) an d some rows have correctly encoded copyright, and if you can distinguish which rows are which, then applying the single-fix vs the double-fix should be 'easy'.
Ditto for columns.  Perhaps the copyright is never in the same column as the Arabic text?
Even messier is when a single cell has both.  That would strongly imply the client is "at fault".


text:
Q: Routing is not working after adding some admin Routes- Elixir
router.ex
defmodule TexasTechWeb.Router do
  use TexasTechWeb, :router
  use Plug.ErrorHandler
  use Sentry.Plug

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_flash
    plug :protect_from_forgery
    plug :put_secure_browser_headers
    plug Guardian.Plug.VerifySession
    plug Guardian.Plug.LoadResource
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  pipeline :graphql do
    plug Guardian.Plug.VerifyHeader, realm: "Bearer"
    plug Guardian.Plug.LoadResource
    plug TexasTechWeb.AbsintheContextPlug
  end

  pipeline :require_login do
    plug Guardian.Plug.EnsureAuthenticated, [handler: TexasTechWeb.Admin.Auth.ErrorHandler]
    plug Guardian.Plug.LoadResource
  end

  scope "/", TexasTechWeb do
    pipe_through :browser

    get "/confirm_email/:code", TokenController, :confirm_email
    get "/reset_password/:code", TokenController, :reset_password
    post "/change_password", TokenController, :change_password # ADDED!
  end

  scope "/admin", TexasTechWeb.Admin, as: :admin do
    pipe_through :browser

    get "/",                                        SessionController, :index
    get "/login",                                   SessionController, :new
    get "/logout",                                  SessionController, :delete
    resources "/sessions",                          SessionController

    pipe_through :require_login

    resources "/users",                             UserController
    resources "/comments",                          CommentsController
    resources "/photos",                            PhotosController
  end

  scope "/api/" do
    pipe_through :graphql
    forward "/graphql", Absinthe.Plug, schema: TexasTechWeb.API.Schema

    forward "/graphiql", Absinthe.Plug.GraphiQL,
    schema: TexasTechWeb.API.Schema
  end

  if Mix.env == :dev do
    forward "/sent_emails", Bamboo.EmailPreviewPlug
  end
end

token_controller.ex
defmodule TexasTechWeb.TokenController do
  use TexasTechWeb, :controller
  alias TexasTech.{Repo, User, Token, UserService}
  import Ecto.Query

IO.inspect "##############Token Controller#############"
  def confirm_email(conn, %{"code" => code}) do
    case Repo.one(fetch_valid_token_q(code, "email_confirmation")) do
      %Token{user: user} = token ->
        case UserService.confirm_and_update_token(user, token, :email_verified_at) do
          {:ok, %{user: _u, token: _t}} ->
            render(conn, "email_confirmed.html")
          {:error, _, _, _} ->
            text(conn, "there was a problem")
        end
      nil ->
        conn
        |> put_status(404)
        |> render(TexasTechWeb.ErrorView, :"404")
    end
  end

  def reset_password(conn, %{"code" => code}) do
    IO.inspect "##########inside rest_password###########"
    case Repo.one(fetch_valid_token_q(code, "password_reset")) do
      %Token{} = token ->
        changeset = User.changeset(%User{}, %{})
        render(conn, "reset_password.html", code: code, changeset: changeset)
      nil ->
        conn
        |> put_status(404)
        |> render(TexasTechWeb.ErrorView, :"404")
    end
  end

  def to_hash(ast) do
    :sha256
    |> :crypto.hash(ast)
    |> Base.encode16
  end

  def change_password(conn, %{"user" => %{"code" => code, "password" => password, "repeated_password" => repeated_password}}) do
    token = Repo.one(fetch_valid_token_q(code, "password_reset"))
    changeset = User.change_password_changeset(token.user, %{password: String.downcase(to_hash(password)), repeated_password: String.downcase(to_hash(repeated_password))})
    if changeset.valid? do
      Repo.update(changeset)
      render(conn, "password_changed.html")
    else
      changeset = User.changeset(%User{}, %{})
      conn
      |> put_flash(:info, "Wrong, try again!")
      |> render("reset_password.html", code: code, changeset: changeset)
    end
  end

  def fetch_valid_token_q(code, type) do
    from t in Token,
      where:    t.code == ^code,
      where:    t.type == ^type,
      where:    t.used == false,
      where:    t.expires_at >= ^Timex.now(),
      join:     assoc(t, :user),

      preload:  :user
  end
end

The three routes confirm_email, reset_password and change_password are not working.
Below is the error I am seeing:

Request: GET /confirm_email/zDiFgI09YDdcdNpkyXiONF2VkXuWVRqv
(UndefinedFunctionError) function
TexasTechWeb.TokenController.confirm_email/4 is undefined or private.
Did you mean one of:

This was working before. This error is happening after adding admin routes.
Anyone please help?


text:
Q: Implement JavaScript options object parameter pattern? There is a common pattern in JavaScript whereby a "constructor" accepts an optional options object. Additionally, that options object may contain only the options the caller wishes to override. For example:
function Foo(options) {
  this._options = {
    foo: 'bar',
    answer: 42,
    amethod: function(){}
  };
  this._options = Object.assign(this._options, options);
}

let foo1 = new Foo();
foo2._options.foo; // 'bar'
foo1._options.answer; // 42
foo1._options.amethod(); // undefined

let foo2 = new Foo({answer: 0, amethod: function(a) { return a; }});
foo2._options.foo; // 'bar'
foo2._options.answer; // 0
foo2._options.amethod('foo'); // 'foo'

Is it possible to implement this pattern in Typescript? If so, how?

A: Here's a more exotic ES6 way to implement default options with destructuring assignment instead of Object.assign():
interface Options {
  foo?: string;
  answer?: number,
  aMethod?: (a:string) => string;
}

class Foo {
    options: Options;
    constructor({
            foo = 'bar',
            answer = 42,
            aMethod = undefined
        }: Options = {}) {
        this.options = { foo, answer, aMethod };
    }
}
var foo1 = new Foo();
console.log("foo1: foo", foo1.options.foo); // 'bar'
console.log("foo1: answer", foo1.options.answer); // 42
console.log("foo1: aMethod", foo1.options.aMethod); // function()
var foo2 = new Foo({answer: 0, aMethod: (a:string) => { return a; } );
console.log("foo2: foo", foo2.options.foo); // 'bar'
console.log("foo2: answer", foo2.options.answer); // 0
console.log("foo2: aMethod", foo2.options.aMethod); // function(a)

Further explanation: http://simonsmith.io/destructuring-objects-as-function-parameters-in-es6/

A: Seems as though you could do this with an Interface with optional members, and using Object.assign as you already have done:
interface Options {
  foo?: string;
  answer?: number,
  aMethod?: (a:string) => string;
}

class Foo {
    options: Options;
    constructor(options:Options) {
        this.options = {
            foo: 'bar',
            answer: 42,
            aMethod: function(){}
        };
        Object.assign(this.options, options);
    }
}
var foo1 = new Foo({});
foo1.options.foo; // 'bar'
foo1.options.answer; // 42
foo1.options.aMethod; // function()
var foo2 = new Foo({answer: 0, aMethod: function(a:string) { return a; } );
foo1.options.foo; // 'bar'
foo1.options.answer; // 0
foo1.options.aMethod; // function(a)

TS Playground Example

A: In Typescript
Let me chime in with a TS answer. In TS, you can of course define the type of the options object, but as of TS 3.2 you can't assign "partial defaults" in the function parameters (i.e. when unset properties of the object will be defaulted to some value).
So this is a real example of a web crawler function, using destructuring. You could also use Object.assign but then for type safety you would have to separately define the type interface for options.
All in all, the only caveat is that you will have to mention those properties twice which will be assigned a default value.
async downloadPageHTML(url: string, options: {
    cookies?: puppeteer.Cookie[],
    launchOpts?: LaunchOptions,
    pageLoadOpts?: Partial<puppeteer.NavigationOptions>,
    userAgent?: string
    browser?: puppeteer.Browser
} = {}) {
    let {
        pageLoadOpts = {},
        launchOpts = {},
        cookies = [],
        userAgent = getUserAgent(url)
    } = options;
    // ...
}


text:
Q: Knock javascript returns nulls to save function Im new to using Knockout for data-binding and MVC, I can retrieve data just fine returning in a Json object, but when I attempt to return user data back and selections to save my values are null. If I separate remove saveContent div and place the save button control in the searchAudio div then I the user input data is returned but I need to return all the form data that the user selects and inputs.
<form action="AudioLookup" method="get" enctype="multipart/form-data">

Audio Playback

                            Bind Audio
                            ID
                            Text
                            Url
                            File Name
                            Prompt Type

                        <input  type="radio" name="adgroup"/>

         <button data-bind="click: getAllAudio">Get Audio</button>

Refine Audio Lookup

        Choice Call Center:
             <select id="CallCenterDLL" data-bind ="value: searchfields.CCCode" name="CallCenterT">
                <option value =""></option>
                <option value = "11">Kansas City</option>
                <option value = "6">Dallas</option>
                <option value = "7">Houston</option>
                <option value = "8">SanAntonio</option>
                <option value = "12">Charlotte</option>
                <option value = "9">Raleigh</option>
             </select>

            Choice Prompt Type:

            <input type="radio" name="RBgroup" value='3' data-bind ="checked: searchfields.searchType"/> Agent

            <input type="radio" name="RBgroup" value='4' data-bind ="checked: searchfields.searchType"/>Office

        <input type="text" name="serchTxt" placeholder="search string Here" data-bind="value: searchfields.searchVal" onblur="minleng(this.value,25);Minimum(this,3);" onkeypress="minleng(this.value,25)"  />
        <button data-bind="click: runQuery">Search Data</button>
           @*
 *@

                        <input type="checkbox" name="select-all" id="select-all"/>Select All

                        <input data-bind="value: PK" class="selectedPK" type="checkbox" />

            @*
*@

 <button data-bind="click: SaveQuery">Save Data</button>

 </form>

function saveViewModel() {
        var self = this;
        var SviewModel = function (CCCode, PK, PKType, SearchType, SearchVal, Text, fileName, aUrl) {
            self.searchfields.CCCode = ko.observable(CCCode);
            self.searchfields.searchType = ko.observable(SearchType);
            self.searchfields.searchVal = ko.observable(SearchVal);
            self.PK = ko.observable(PK);
            self.PKType = ko.observable(PKType);
            self.Text = ko.observable(Text);
            self.fileName = ko.observable(fileName);
            self.aUrl = ko.observable(aUrl);

        }

        self.state = ko.observable();
        self.dataResult = ko.observableArray();
        self.SaveQuery = function () {
            alert(ko.toJSON(SviewModel));
            $.ajax(
        {
            url: "/CallCenter/SaveQuery",
            contentType: "application/json",
            type: "POST",
            dataType: "json",
            data: ko.toJSON(self.dataResult),
            success: function (data) {
                self.SaveResult(data);
            }
        });
        }
    }

A: you alert :-
alert(ko.toJSON(SviewModel));

the data you send :-
data: ko.toJSON(self.dataResult),

and that is :-
self.dataResult = ko.observableArray();

which seems unused.... so not too surprising everything is null


text:
Q: BeautiulSoup4 Installation issue in VSCode I've BeautifulSoup4 installed in my system but when I import it, I get thrown an error No module named 'beautifulsoup4'. I just installed this module as shown in the screenshot  attached. .
In addition, I've tried the regular pip install method to install BeautifulSoup4 but same issue.

A: Maybe you are not in the version you installed beautifulSoup4. Try positioning yourself in the python version you intalled it.

A: try changing the version you are working on with in visual:
Look for this, and click it
you may have two options like so:
select the one you are not positioned in


text:
Q: Using jQuery delegate() to replace live() I currently am creating content using jQuery.
Live(), according to the jQuery API Description: Attach an event handler for all elements which match the current selector, now and in the future..  I need this line of code to work in the future.
$(".trash").delegate('.delete_gallery', 'click', function(event) { // does not work
$(".delete_gallery").live("click", function(event) { // works
How can I get the delegate to work?  I don't want to use a deprecated function.
.on() is not a choice.  Hopefully this isn't a duplicate question either, I couldn't find any that addressed this, they all just say how to do it.
Thanks!
Jacob

A: try
$(document).delegate('.delete_gallery', 'click', function(event) {

A: You'd be better delegating the event handler to $(document) rather than $(".trash') as it means you're not relying on it existing.

A: You still have .bind().
Example
$(".trash").bind('click', function(event) {


text:
Q: Per-tag breakdown of reputation in answers I posted this as an answer to another question, but after some thought, I think it qualifies as a feature request in its own right.
I would like to see a per-tag breakdown (based on a question's tag list) of each answerer's reputation in addition to their lump sum reputation.  Something like this:
Question is tagged with:

C# winforms combobox

An answer would look like this:

Blah blah blah

Eric 200   C#170    winforms50    combobox10

This would give more insight into how credible a person's answer is.  I think it will also be more rewarding for people that are more active in less popular tags.  I'm not sure how difficult it would be to implement though.

A: Two problems:

*

*Reputation is no measure of expertise;

*When you earn upvotes beyond the daily rep cap, you will get no rep for the votes and thus less reputation than you might otherwise deserve in this measure. This is a significant issue for some who earn many upvotes beyond the daily rep cap.

A: An interesting idea, but in reality there would be very few tags that would be interesting to see. I mean there are around 26k tags on stackoverflow, but you are not interested in seeing the reputation of all of them. Often there is one or two main tags along with some that are uncommon but good for the semantic of the question. If such a feature should be implemented I would suggest that it only would be applied for the most common of the tags or the tag that is listed first. So that in the above example what's really interesting is the persons reputation in c#, not how many questions about combobox he has answered.


text:
Q: ¿Cómo excluir resultados de un query con mysql? Tengo dos tablas de la base de datos usuario y network en Mysql. Donde network es una tabla pivote para relacionar dos usuarios entre sí.
La entidad de usuario contiene información como id, nombre, password, etc.
La entidad network contiene dos id de usuarios: origen y amigo.
Necesito hacer un query para buscar usuarios por nombre o correo electrónico, pero excluyendo de la búsqueda los usuarios que se tengan agregados entre sí. Es decir, si el usuario con el id 93 tiene que excluir de la búsqueda los usuarios que ya tenga agregados en la tabla de network.
Si en mi tabla network tengo la siguiente información para el usuario 93:
+--------+-------+
| origen | amigo |
+--------+-------+
|     82 |    93 |
|     83 |    93 |
|     90 |    93 |
|     93 |   178 |
|     93 |   208 |
|     93 |   209 |
|    210 |    93 |
+--------+-------+

¿De qué manera puedo modificar mi query para excluir de la búsqueda los usuarios que están relacionados con el id 93 a través de la tabla de network? Ejemplo: El usuario con id 93 hace la búsqueda con roberto. Donde ${texto} representa la cadena texto a buscar.
SELECT
  u.id,
  u.nombre,
  u.apellido
FROM usuario as u
WHERE
  CONCAT(u.nombre, ' ', u.app) LIKE '%${texto}%'
  OR u.email LIKE '${texto}%'

A: Creo que en este caso, ayuda un poco expresar el problema en lenguaje natural. Yo diría que estás buscando a todos los usuarios que no sean amigos de un usuario particular. Yendo un poco a lo técnico, agregaría que un usuario es amigo de otro cuando existe un registro en la tabla network que los relaciona, sin importar quien aparece en el campo origen y quién aparece en el campo amigo.
En otras palabras, los amigos de un usuario es la unión de los origenes cuando el amigo es el usuario de mi interés, con los amigos cuando el origen es usuario de mi interés, dicho en SQL:
select amigo from network where origen = 93
union
select origen from network where amigo = 93

Luego, para encontrar todos los usuarios que no son amigos de 93, podemos valernos de la operación not in y la consulta sería algo como:
select *
  from usuario
 where id != 93
   and id not in (select amigo from network where origen = 93
                  union
                  select origen from network where amigo = 93
                 )

He excluido al propio usuario, pues en este caso, supongo que el usuario tampoco puede ser su propio amigo (asumiendo que la búsqueda es para mostrar los candidatos a poder ser amigos de alguien).

A: Pudieras utilizar NOT IN, para negar todos los registros que coincidan con el campo network.amigo a través de una subconsulta y después agregar un AND en las comparaciones de texto que tienes:
SELECT
u.id,
u.nombre,
u.apellido
FROM usuario u
WHERE
  u.id NOT IN (SELECT n.amigo
               FROM   network n
               WHERE  n.origen = u.id
              )
AND (
        CONCAT(u.nombre, ' ', u.app) LIKE '%${texto}%'
        OR u.email LIKE '${texto}%'
    )


text:
Q: How to count up a value until all geometry features from one table are selected For example, I have this query to find the minimum distance between two geometries (stored in 2 tables) with a PostGIS function called ST_Distance.
Having thousands of geometries (in both tables) it takes to much time without using ST_DWithin. ST_DWithin returns true if the geometries are within the specified distance of one another (here 2000m).
SELECT DISTINCT ON
    (id)
    table1.id,
    table2.id
    min(ST_Distance(a.geom, b.geom)) AS distance
FROM table1 a, table2 b
    WHERE ST_DWithin(a.geom, b.geom, 2000.0)
        GROUP BY table1.id, table2.id
        ORDER BY table1.id, distance

But you have to estimate the distance value to fetch all geometries (e.g. stored in table1). Therefore you have to look at your data in some way in a GIS, or you have to calculate the maximum distance for all (and that takes a lot of time).
In the moment I do it in that way that I approximate the distance value until all features are queried from table1, for example.
Would it be efficient that my query automatically increases (with a reasonable value) the distance value until the count of all geometries (e.g. for table1) is reached? How can I put this in execution?
Would it be slow down everything because the query needs maybe a lot of approaches to find the distance value?
Do I have to use a recursive query for this purpose?

A: See this post here: K-Nearest Neighbor Query in PostGIS
Basically, the <-> operator is a bit unusual in that it works in the order by clause, but it avoids having to make a guess as to how far you want to search in ST_DWithin. There is a major gotcha with this operator though, which is that the geometry in the order by clause must be a constant that is you CAN NOT write:
select a.id, b.id from table a, table b order by geom.a <-> geom.b limit 1;

Instead you would have to create a loop, substituting in a value above for geom.b
More information can be found here: http://boundlessgeo.com/2011/09/indexed-nearest-neighbour-search-in-postgis/


text:
Q: Facebook browser on iOS: problems with localStorage Localstorage for our webapp (react) behaves strange when the site is opened in the Facebook browser on iOS and android. We have an authentication flow that depends on storing a token in localstorage and reading it. The symptoms we see when our site is opened in the facebook browser (a user clicks on a link to our site on Facebook) is that the auth flow fails on the first attempt at login but works on the second attempt at login. It appears like the localstorage is asyncronous. At least it behaves differently from other browsers like Chrome, Firefox and Safari.
I have tried to do a setTimeout of up to 700 ms before redirecting after login, but it still fails to read the token from localstorage.
I am however able to do localstorage.getItem(key) immediately after localstorage.setItem(key, value) and get the expected result.

A: If somebody has problems with localStorage in Fasebook in-app browser, please make sure that you set strings to variables in localStorage (not numbers, boolean, etc.). This is a simple rule but sometimes you forget about it when you don't get errors.
This my code worked in smarty Chrome but didn't work as expected in Facebook browser because the exp variable was a number:
window.localStorage.setItem("exp", exp);

But this code worked well in both browsers:
window.localStorage.setItem("exp", ''+exp);


text:
Q: Notation in Financial Math I am very close to showing part b of this question and think that the reason my solution doesn't match up is because I don't understand a piece of notation.The notation I don't understand is $\textbf{$e^T$}$ on the bottom line inside the function $h$.
I am at the point:
$$E[f(W)] = \frac{1}{a}\huge{[}\normalsize 1 - \exp\{-aw\xi_0 r_0 + aw\big(\frac{1}{2}aw\xi V\xi^T - \xi r^T\big)\}\huge{]} $$


text:
Q: A change made locally to observer in development mode not happening when deployed to production? After updating the code I ran the following:
bin/magento setup:static-content:deploy
bin/magento setup:di:compile
bin/magento deploy:mode:set -s production
bin/magento index:reindex
bin/magento cache:flush

The change was made in an Observer
The problem is that no matter what I do, even disabling the module entirely the change does not happen on a dropdown.
Is there more I should be doing for a complete deploy? Maybe Opcache is keeping it?

A: The problem was opcache
You need to flush it with Opcache reset

A: I found running the below always helped clear the site and load the latest PHP code
bin/magento setup:upgrade


text:
Q: pytest-selenium: pytest_selenium_capture_debug hook is not fired on test failure I make e2e tests for an web app by using pytest and selenium. Everything is fine, but one thing I can't figure out though spent day searching the web.
I can't make pytest_selenium_capture_debug work. I put it in conftest.py in the root of the test sources. Tests are run inside docker container. Firefox runs with xvfb-run. I record screen video and want copy it to the host if test fails.
I use python 3.6.11 and these library versions are
pytest==6.2.4
pytest-base-url==1.4.2
pytest-helpers-namespace==2021.4.29
pytest-html==3.1.1
pytest-lazy-fixture==0.6.3
pytest-metadata==1.11.0
pytest-repeat==0.9.1
pytest-selenium==2.0.1
pytest-variables==1.9.0
selenium==3.141.0

A: The issue caused by using custom_selenium fixture. To make all the pytest-selenium hooks work properly it's necessary to use selenium fixture defined by pytest-selenium as is follows.
@pytest.fixture
def logged_in_selenium(selenium):
    ...


text:
Q: to_csv does not generate desired output of data frame converted from list I have a list of data frame output as below:
[           contig                             read_name  position reference_kmer  event_level_mean  event_stdv       count
0    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99         1          CACAT         78.400000    1.079000    15.04458
1    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99         2          ACATC         84.570000    1.173000    10.02972
2    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99         3          CATCA        101.207332   13.997181   106.30899
3    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99        13          TACCC         80.260000    2.824000    11.02665
4    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99        14          ACCCG         69.084390    1.138712    27.06816
5    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99        15          CCCGG         75.963461    2.477512    31.08609
.
.
.]

I want to write this list to file. So I first converted the list to data frame and write to a file name out.txt. I executed the commands below:
result = pandas.DataFrame(output)
result.to_csv('out.txt', index=False, sep = "\t")

However, the head of tail of the file out.txt showed extra 0 and double quotation ".
0
"           contig                             read_name  position reference_kmer  event_level_mean  event_stdv       count
0    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99         1          CACAT         78.400000    1.079000    15.04458
1    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99         2          ACATC         84.570000    1.173000    10.02972
2    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99         3          CATCA        101.207332   13.997181   106.30899
3    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99        13          TACCC         80.260000    2.824000    11.02665
4    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99        14          ACCCG         69.084390    1.138712    27.06816
5    gblock_Gmod2  12212f92-6610-410a-b317-bc2ca3f57f99        15          CCCGG         75.963461    2.477512    31.08609
.
.
."

How do I get rid of the 0 and "? Thanks.


text:
Q: When is a trigger fired? My portal will be picking data every 2 hours from a file to a SQL Server table, lets say TableSource. As data is received in TableSource, it should also be copied into TableDestination, so we wrote a trigger for it.
My question is: what is the interval or rate of triggers getting fired in SQL Server? Will it be fired for each row (like MySQL), or after 500 inserts or after completion of all the inserts?
Data will be inserted in bulk, not manual entries.. maybe like 40k - 50k per hour. Can I run my trigger only once, after all my 40K are completely inserted into TableSource?

A: On a FOR/AFTER type trigger, it gets fired immediately after each insert, update or delete statement, prior to commit.
An INSTEAD OF trigger works differently and actually provides alternate logic for your insert, update or delete.  It fires in place of your insert, update or delete statement.  In this case it doesn't sound like the right approach.
Use the inserted or deleted logical tables to capture the results of the insert or delete. Since you are doing bulk inserts, make sure to write the trigger to handle multiple rows at a time.
I'm not a big fan of the approach but I've seen a lot of developers using cursors in triggers. That tends to have negative performance impacts so I usually stick to normal insert statements.
One additional point, though, which I should clarify: if you are actually using the T-SQL BULK INSERT statement, it's possible that triggers will be skipped. There is an override, FIRE_TRIGGERS that you will want to make sure to use. From that documentation link:

FIRE_TRIGGERS
  Specifies that any insert triggers defined on the destination table execute during the bulk-import operation. If triggers are defined for INSERT operations on the target table, they are fired for every completed batch.
If FIRE_TRIGGERS is not specified, no insert triggers execute.

A: From Controlling Trigger Execution When Bulk Importing Data

A trigger is a special form of stored procedure that is executed automatically when a user modifies data in a table or view.
[...]
If triggers are enabled, they are executed once for each batch.

You can also track the behavior of the triggers. So you can make triggers to be executed only once per bulk import operation.
Another solution is to create a stored procedure, which will do exactly the same things that you are doing inside your triggers. You can call that SP after the bulk import operation completes in the same transaction.

BULK INSERT is a T-SQL command. Whenever you write a bulk insert you can specify the BATCHSIZE parameter:

BATCHSIZE = batch_size
Specifies the number of rows in a batch. Each batch is copied to the server as one transaction. If this fails, SQL Server commits or rolls back the transaction for every batch. By default, all data in the specified data file is one batch.


text:
Q: django forms Dynamic choicefield list choices value  Problem
I change my approach...
My url : passing my_code on it
(r'^test_form_2/(?P<my_code>\d+)/$', TestForm_2),

My views : grab the my_code to choose the right choice list on the dic_list
def TestForm_2(request,my_code):

    dic_list = {'1':(('1','A'),('2','B'),('3','C')),
                '2':(('1','D'),('2','E'),('3','F')),
                '3':(('1','G'),('2','H'),('3','I'))
                }

    if request.method =="POST" :
        form = TestForm2(request.POST)

        if form.is_valid():

            return HttpResponse ('OK')

    else :

        my_choices_list = dic_list[my_code]
        form = TestForm2(my_choice=my_choices_list)

    return render_to_response ('zip_finder/page_form.html')

and the form :
class TestForm2(forms.Form):

    my_select = forms.ChoiceField(choices='',label='Choisissez dans la liste')

    def __init__(self, my_choice=None, **kwargs):
        super(TestForm2, self).__init__(**kwargs)
        if my_choice:

            self.fields['my_select'] = forms.ChoiceField(choices=my_choice,label='Choisissez dans la liste')

I click submit and then :
Caught ValueError while rendering: too many values to unpack

I have a look to the HTML and can't see the selected option on my selection :
 <select id="id_my_select" class="select" name="my_select">
<option value="1">D</option>
<option value="2">E</option>
<option value="3">F</option>
</select>

SOLUTION : Use ModelChoiceField
My url : passing my_code on it
  (r'^test_form_2/(?P<my_code>\d+)/$', TestForm_2),

My views : grab the my_code to choose the right choice list on a queryset object
 def TestForm_2(request,my_code):

        if request.method =="POST" :
            form = TestForm2(request.POST)

            form.fields['ville_source'].queryset = Villes.objects.filter(code_postal=my_code)
            if form.is_valid():

                return HttpResponse ('OK')

        else :

            form = TestForm2(my_code=my_code)

        return render_to_response ('zip_finder/page_form.html')

My form :
class TestForm4(forms.Form):

    ville_source = ModelChoiceField(queryset=Villes.objects.all(),required=True,label='Choisissez votre ville source')

    def __init__(self, *args, **kwargs):
        code_postal = kwargs.pop('my_code', None)
        super(TestForm4, self).__init__(*args, **kwargs)

        if code_postal:

            self.fields['ville_source'].queryset = Villes.objects.filter(code_postal=code_postal)

A: *

*Queryset lst_ville is empty, it must be filtering like this, using the unicode value of code_postal:
.filter(code_postal='<django.forms.fields.CharField object at 0x26bf550>').

*Use ModelChoiceField instead of CharField:
# make sure that lst_ville is not an empty queryset
ville_source = forms.ModelChoiceField(queryset=lst_ville,label='Choisissez votre ville source')

*For field filtering based on the value of another field of the form, it becomes a little complicated. The simplest solution for you is to just use django-selectables or django-autocomplete-light.


text:
Q: import pygr into jython failing on C library I am trying to import pygr:
It fails on:
>>> import seqfmt
ImportError: No module named seqfmt

The program that uses this works fine in Python.  However its calling a C library called seqfmt (which has a C file and a PYX files).  Is this possible to import over to Jython or since its C am I out of luck?

A: .PYX is the file extension used by cython, a tool for writing C extensions for python in a python-like syntax. Cython creates an intermediate file (that's presumably the .C file you see, at least it's not in the git repository) and compiles it into a python extension.
Jython does not support CPython extensions yet. From its homepage:

There are a number of differences. First, Jython programs cannot currently use CPython
  extension modules written in C. These modules usually have files with the extension .so,
  .pyd or .dll. If you want to use such a module, you should look for an
  equivalent written in pure Python or Java. However, it is technically
  feasible to support such extensions, as demonstrated by IronPython.
  For the next release of Jython, we plan to support the C Python
  Extension API.

Some cython modules can be easily translated into python, and seqfmt is one of them, but pygr has a second cython module, cnestedlist, which involves C calls: The lines
cdef extern from "apps/maf2nclist.h":
[..]
int readMAFrecord(IntervalMap im[],int n,SeqIDMap seqidmap[],int nseq,
                int lpoStart,int *p_block_len,FILE *ifile,int maxseq,
                long long linecode_count[],int *p_has_continuation)

define an external library call. You'd have to translate this library to Python, too.
Just as a side-note regarding the translation: cython can not only be used to wrap C libraries, but also to simply speed up certain parts of a program. In these cases it is pretty straight-forward to translate them into a python module. Have a look into the seqfmt.pyx source file, its pretty self-explanatory if you know python.
That all being said, there is a project related to Jython, JyNI, which aims to support CPython extensions from Jython. It is work-in-progress, so I can't tell if your libraries are supported by it. There are some examples in the github repository, maybe you can get it to work. The readme file claims binary compatibility, so with JyNI enabled you should be able to run your code without any recompiling.


text:
Q: Does anyone know how to upload a file from within Salesforce up to an existing Box folder? We are using the Box Widget in our Salesforce client and this allows our users to easily upload files to Box' system.  However, we also need to upload files that may have been added by users as attachments to various objects.
Every example I've seen so far shows a Rest service sending a form POST where the intended file was received from within the browser using  tags.  However, the apex method wasn't triggered by a FormPost.
Certainly we can retrieve the Attachment object, and I know how to create a Rest Service to call Box's API, but I don't know how to simulate a file upload when we only have apex Blobs to send.


text:
Q: searching the strings using starting characters in Jlist? I am creating a search list in java. If I enter the beginning letters, then the corresponding words which belongs to the letters will be display on the Jlist.For that is there any build in methods is there? Then how can i search the words with starting characters? Suggest me.
Thank in advance..

A: SwingX has some nice features, including autocomplete. You can get it here
This is how you can use it:
JTextField textField = new JTextField();
textField.setText("Remi");

Vector v = new Vector();
v.add("Jimmy");
v.add("Julie");
v.add("Julien");
v.add("Juliette");

JList list = new JList(v);
Configurator.enableAutoCompletion(list, textField);


text:
Q: On what Oracle distribution is the 64-bit oracle.dataaccess.dll is found? I would like to know on what oracle distribution is the 64-bit oracle.dataaccess.dll is found.  So far I have downloaded 64-bit Oracle10g Release 2 ODAC for Windows x64   ODAC10203x64.zip and Oracle Database 11g Release 1 (11.1.0.7.0)
for Microsoft Windows Server 2008 x64 but the dll is not present.
Thanks in Advance

A: Here is the download on OTN:
http://www.oracle.com/technetwork/database/windows/downloads/index-090165.html
It's also available on metallink: download the latest 64-bit 11.2 database patchset.
Christian Shay
Oracle

A: From what i know, the 64bit ODAC 11g can be downloaded through oracle metalink. The 64 bit version is a separate installer from the 32bit version (which can be downloaded freely). You need to have a metalink account to login.


text:
Q: Вставка ссылки viber на сайт Вставил ссылку на viber  но при переходе в само приложение viber отображается:

A: Для Viber

телефон в формате +(код страны) номер. + заменить на %2B


text:
Q: Как прервать завершение Fragment Всем привет.
Во время завершения, я в  onPause() проверяю, все ли поля были корректно заполнены.
Если нет то хотелось, что бы пользователь не смог нажать назад, пока все условия не будут соблюдены.
Как это можно сделать?

A: Мне кажется, вам нужно переопределить метод onBackPressed()
К примеру:
@Override
public void onBackPressed() {
    //Если поля не заполнены, то показать какое нибудь сообщение
    //иначе
        super.onBackPressed();
}


text:
Q: R library not getting loaded when I try this using statConnector in R I can access the basic function of stat library in R when I connect C# and R through statconnector. But if I load a library(), I am not able to call any of its function.
The code I am trying is:
rConn.SetSymbol("n1", 20);
rConn.Evaluate("library(dtw)");
rConn.Evaluate("x1<-rnorm(n1)");
rConn.Evaluate("x2<-rnorm(n1)");
rConn.Evaluate("Score<-dtw(x1,x2,keep.internals=TRUE)");

The error I get is when I run the last line i.e., rConn.Evaluate("Score<-dtw(x1,x2,keep.internals=TRUE)");
The error i get is -
There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))

A: You will find that with some functions called via StatConnector that you MUST use .EvaluateNoReturn instead of .Evaluate. It makes sense if you recognize that if you examine the class of "Score" (within R) via:
class(Score)
[1] "dtw"

You see that "Score" contains a dtw object. Implicitly whenever you use .Evaluate, you are calling a function with a return value. However, C# doesn't know what to do with a dtw object, so you get a funky error message that make you go hmmm. Try the equivalent of a void call instead:
rConn.EvaluateNoReturn("Score<-dtw(x1,x2,keep.internals=TRUE)");

And you should have no error executing dtw. To get a return value back into C#, while in R, take a look at names(Score) to see which variables are available, then something like
class(Score$normalizedDistance)
"numeric"

to get an idea how to cast the values for C#, as in:
double myDist = (double)rConn.Evaluate("Score$normalizedDistance");

A: Additional information I found that I received a similar error when calling 10+ concurrent statconnector instances.
The .Evaluate function when returning values would fail on 10% of calculations with the following error
There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))
   at StatConnectorCommonLib.IStatConnector.Evaluate(String bstrExpression)

The fix I found to work was to store the result in a variable in R, and use the .EvaluateNoReturn and .GetSymbol to return the results.
StatConnector rConn = new StatConnector();

rConn.Init("R");
rConn.SetSymbol("n1", 20);
rConn.Evaluate ("x1<-rnorm(n1)");
var o = rConn.GetSymbol ("x1");

foreach (double d in o)
    Console.WriteLine(d);

rConn.Close();

Check out the following article for my source and examples,
http://www.billbak.com/2010/11/accessing-r-from-clessons-learned/


text:
Q: how to use getDerivedStateFromProps In my application, I want to navigate to dashboard screen, if the user logs in from the login screen. My code is like this.
// Login Screen

     componentDidUpdate() {
          const { auth, history } = this.props;
          redirectIfAuthenticated(auth.isAuthenticated, history, './dashboard');
       }

       static getDerivedStateFromProps = (nextProps, prevState) => {
          if (nextProps.errors)
             return { errors: nextProps.errors }

          return { errors: prevState.errors }
       }

// auth util
export const redirectIfAuthenticated = (isAuthenticated, history, screen) => {
   if (isAuthenticated) {
      history.push(screen);
   }
}

this works as expected. I want to know if im doing this in the right way. I replaced componentWillRecieveProps with getDerivedStateFromProps. Now I have to use componentDidUpdate as well to achieve what I did with componentWillRecieveProps. Is this correct

A: Yes, this is how you should do it. Take a look at the getDerivedStateFromProps's documentation
Also, you can return null to avoid updating the state so I would change the prevState.errors part into this :
 static getDerivedStateFromProps = (nextProps, prevState) => {
          if (nextProps.errors) {
             return { errors: nextProps.errors }
          } else {
           return null
          }
       }


text:
Q: Using Controller.Content Outside MVC Controller c# I'm creating a static class with static methods for helping the controllers to do their job. When build the application I get the following error:

Error 40 'System.Web.Mvc.Controller.Content(string)' is inaccessible due to its protection level"

Any idea how to solve this problem?
Notes:
It's a c# mvc aplication
public static ActionResult GetAlbumJSON(AlbumVO album)
{
    return Controller.Content(
        JsonConvert.SerializeObject(new
        {
            max_car = @ABookClient.maxCharsProjecName,
            trans_img = @ABookClient.Transparent_Image,
            show_description = @ABookClient.Show_Product_Description,
            product_type = "Album",
            obj = CreateObjAlbumVO(album),
        })
    );
}

A: Content method is protected internal, so you can't use it outside of controller.
Controller.Content Method. Most probably your static class violates SRP principle. Let him do his job (initializing, serializing,...) and controller - controller's job - return result to the client.
protected internal ContentResult Content(string content)

It would look smth like:
public static class MyHelper
{
    public static object GetAlbum(AlbumVO album)
    {
        return new
            {
                max_car = @ABookClient.maxCharsProjecName,
                trans_img = @ABookClient.Transparent_Image,
                show_description = @ABookClient.Show_Product_Description,
                product_type = "Album",
                obj = CreateObjAlbumVO(album),
            };
    }
}

public class AlbumController : Controller
{
    public ActionResult GetAlbums(int id)
    {
        var album = Context.GetAlbum(id);
        var convertedResult = MyHelper.GetAlbum(album);
        return Json(convertedResult);
    }
}

Also I'd advice to take a look at AutoMapper for creating client response objects

A: I think this is valid case for a view-model for a JSON result since you do want a separation between the Domain model and the data sent back to the client. Using a view model also gives you a proper place to put this mapping between the domain model and the view (the JSON) so you don't need to delegate to a helper class.
public class AlbumModel
{
    [JsonProperty(PropertyName = "max_car")]
    public int MaxChars { get; private set; }
    [JsonProperty(PropertyName = "trans_img")]
    public string TransparentImage { get; private set; }
    [JsonProperty(PropertyName = "product_type")]
    public string ProductType { get; private set; }
    [JsonProperty(PropertyName = "obj")]
    public AlbumInfo Object { get; private set; }
    [JsonProperty(PropertyName = "show_description")]
    public bool ShowProductDescription { get; private set; }

    public AlbumModel(AlbumVO album)
    {
        MaxChars = album.maxCharsProjecName;
        TransparentImage = album.Transparent_Image;
        ShowProductDescription = album.Show_Product_Description;
        ProductType = "Album";
        Object = new AlbumInfo(album);
    }
}

The AlbumInfo class provides additional mappings for your JSON result, which becomes the "obj" property sent back to the client.
public class AlbumInfo
{
    // ... define properties here
    public AlbumInfo(AlbumVO album)
    {
        // ... map properties here
    }
}

And your controller becomes nice and clean:
public class AlbumController : Conrtoller
{
    public ActionResult GetAlbums(int id)
    {
        var album = Context.GetAlbum(id);
        var model = new AlbumModel(album);
        return Json(model);
    }
}


text:
Q: When the image of a homomorphism of Lie Algebras is an ideal? Let $\mathfrak{g}_{1}$, $\mathfrak{g}_{2}$ be Lie algebras and
$$ \varphi : \mathfrak{g}_{1} \rightarrow \mathfrak{g}_{2} $$
be a homomorphism of Lie algebras. Somebody could tell me (proof) a necessary and
sufficient condition on $\varphi$ to ensure that $\mbox{Im}\varphi$ be an
ideal of $\mathfrak{g}_{2}$?
I would be happy with any suggestion. Thank you!

A: It is easy to give a sufficient condition, mamely that $\phi$ is surjective. In this case, $\phi(I)$ is an ideal in $\mathfrak{g}_2$ for any ideal $I$ in $\mathfrak{g}_1$, because
$$
[\mathfrak{g}_2,\phi(I)]=[\phi(\mathfrak{g}_1),\phi(I)]=\phi([\mathfrak{g}_1,I])\subseteq \phi(I).
$$
However, this is not a necessary condition. For, say, $\phi=0$ and $\mathfrak{g}_2\neq 0$, we have that $\phi(I)$ is an ideal, although $\phi$ is not surjective.


text:
Q: Mockito - test method inside a nethod I'm trying to test my Utils class. Some of the methods use other class methods. I want to mock the internal methods use so the test will assume they work (in order to make it real Unit test, which test the specific method).
I want to test 'buildUrl' method:
 public static String buildUrl(String path, List<Pair> queryParams, DateFormat dateFormat) {
    final StringBuilder url = new StringBuilder();
    url.append(path);

    if (queryParams != null && !queryParams.isEmpty()) {
        // support (constant) query string in `path`, e.g. "/posts?draft=1"
        String prefix = path.contains("?") ? "&" : "?";
        for (Pair param : queryParams) {
            if (param.getValue() != null) {
                if (prefix != null) {
                    url.append(prefix);
                    prefix = null;
                } else {
                    url.append("&");
                }
                String value = Utils.parameterToString(param.getValue(), dateFormat);
                url.append(Utils.escapeString(param.getName())).append("=").append(Utils.escapeString(value));
            }
        }
    }

    return url.toString();
}

BuildUrl uses 'parameterToString' (and others) which I want to mock for the test. So I tried something like this:
 @Test
public void testBuildUrl(){
    Utils util = new Utils();
    Utils utilSpy = Mockito.spy(util);
    Mockito.when(utilSpy.parameterToString("value1",new RFC3339DateFormat())).thenReturn("value1");
    List<Pair> queryParams = new ArrayList<Pair>();
    queryParams.add(new Pair("key1","value1"));
    String myUrl = utilSpy.buildUrl("this/is/my/path", queryParams, new RFC3339DateFormat());
    assertEquals("this/is/my/path?key1=value1&key2=value2", myUrl);
}

But I'm getting MissingMethodInvocationException from Mockito.
So my question is actually - how to mock a method that has been invoked within the tested method, and what's wrong with my test. Thanks.

A: You cannot mock / spy static invocations using standard Mockito.
You will have to use Powermockito and something to the following:
@RunWith(PowerMockRunner.class)
@PrepareForTest(Utils.class)
public class MyClassTest{

    @Test
    public void testBuildUrl(){
         PowerMockito.mockStatic(Utils.class);

         // mock the static method to return certain values
         Mockito.when(Utils.parameterToString("value1",new RFC3339DateFormat()))
             .thenReturn("value1");
         Mockito.when(Utils.escapeString(anyString()).thenReturn(desiredResult);

       // rest of test code
    }

Here is some more stuff to read through -> powermockito static

A:
I want to mock the internal methods use so the test will assume they work (in order to make it real Unit test, which test the specific method).

UnitTests do not test specific methods.
UnitTests test public observable behavior of the code under test.

If you feel you should mock some of the methods this could be a sign that your design needs improvement. There is no need to make utility methods static and maybe your Class under test has to much responsibilities.
Of cause PowerMock will overcome the problems in your test but IMHO the use of PowerMock is a surrender to bad design.


text:
Q: Can you programatically create an expression when setting a property in WSO2? I have the a case where we accept 'JSON'-like code into an API, there is a problem with one case, where a customer has a numeric ID as a fieldname.
eg.
{
  "Node1": {
     "123456": [
        {
         "Field1": "Value1",
         "Field2": "Value2"
        },
        {
         "Field1": "Value3",
         "Field2": "Value4"
        }
     ]
  }
}

Now, trying to set the array to a property works if I hardcode in 123456
<property name="fields" expression="json-eval($.Node1.123456)" scope="default" type="STRING"></property>

but I need somehow to dynamically set this expression. I have a reference to the id in question as a property value.
Is it possible to dynamically construct an expression so I can set this json as a property?
ie. something like
 <property name="myid" value="123456"/>
 <property name="fields" expression="fn:concat('json-eval($.Node1.', get-property('myid'))" scope="default" type="STRING"></property>

Could it be done converting the message to XML and somehow referencing it there and converting back to json?
Thanks!

A: It's possible using Property Mediator with Script Mediator.
Here is an example:

 <property name="payload" expression="json-eval($.)"/>
 <property name="myid" value="123456"/>
 <property name="HARDCODED" value="none"/>
 <script language="js">

    var myid = mc.getProperty("myid");

    // you can interate your payload if needed
    var payload = mc.getProperty("payload");

    // Or just make a String of it
    var json = '{ "Node1" : { "' + myid + '": [{ "Field1": "Value1", "Field2": "Value2" }] } }';

     mc.setProperty("HARDCODED", json);

 </script>
 <payloadFactory media-type="json">
    <format>$1</format>
    <args>
       <arg evaluator="xml" expression="get-property('HARDCODED')"/>
    </args>
 </payloadFactory>

With JavaScript you can go right to it.
Hope it helps.

A: I was able to do this through a roundabout way. I had to modify the message after it arrived using my own Mediator..
In the code below, I'm just taking the 1st occurance as an example
public class MyMediator extends AbstractMediator {
  .
  .
  public boolean mediate(MessageContext mc) {
    OMFactory factory = OMAbstractFactory.getOMFactory();

    SOAPBody b = mc.getEnvelope().getBody();
    Iterator it = b.getFirstElement().getChildrenWithLocalName("Node1");
    if(it.hasNext()){
        OMElement obj = (OMElement)it.next();
        Iterator w_it = obj.getChildElements();
        if(w_it.hasNext()){
            OMElement cfield = (OMElement)w_it.next();
            cfield.setLocalName("Order");
            .
            .
        }
       ((OMContainerEx)b).setFirstChild(obj);
     }
  }
  .
  .
}

I could then get the id and create a new OMElement with the ID and rename the element something meaningful like 'Order'
So now I can reference this using a json path and set it as a property
eg.
<property name="fields" expression="json-eval($.Order)" scope="default" type="STRING"></property>

In my case, the id is also in the fields of the Order .. so it's not an issue for me, but if you needed to, when you are renaming the node, you could store the existing name (ie. 12345) as a value by creating a new OMElement and adding it to your obj
the '((OMContainerEx)b).setFirstChild(obj);' is optional .. I didn't care for the previous paths so just dropped them.
Hope this helps someone (or someone comes back with a better idea ;) )


text:
Q: CSS transform hides floated element above it I'm making a simple blog post box with am image at the top. When the mouse hovers over the box the image scales to 1.1 and the overflow is hidden.
The blog post DIV is set to relative and I have icon above the image that is set to absolute so it sits half on the top of the image and half above it.
The problem:
When the mouse hoovers over the DIV, the images scales as it should but the part of the icon that sits over the image disappears.
How can I stop this, so that the icon remains visible when the scale transform is happening?
Thanks for the help.
HTML

xxx

xxxxxxxxx

xxxxxxxxxxxx

...

Read More

and the CSS
.blog_icon {
  width: 100%;
  height: 100%;
  position: absolute;
  top: -25px;
  left: 0;

}

.blog_slot    {
    position: relative;
    max-width:500px;
    min-width:200px;
    border-style: solid;
    border-width: 5px;
    border-color: #FFD657;
    text-align: center;
    }

.blog_image
{

    overflow: hidden;}

.blog_image img {
    width:100%;
    max-width:450;
    height:100%;

  -moz-transition: all 0.5s;
  -webkit-transition: all 0.5s;
  transition: all 0.5s;

}

.blog_slot:hover .blog_image img {

  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}

A: Hope this solves your problem. I have added a z-index to .blog-icon.

.blog_icon {
  width: 100%;
  height: 100%;
  position: absolute;
  top: -25px;
  left: 0;
  z-index: 1;
}
.blog_slot {
  position: relative;
  max-width:500px;
  min-width:200px;
  border-style: solid;
  border-width: 5px;
  border-color: #FFD657;
  text-align: center;
}

.blog_image {
  overflow: hidden;
}

.blog_image img {
  width:100%;
  max-width:450;
  height:100%;

  -moz-transition: all 0.5s;
  -webkit-transition: all 0.5s;
  transition: all 0.5s;

}

.blog_slot:hover .blog_image img {
  -moz-transform: scale(1.1);
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}

xxx

xxxxxxxxx

xxxxxxxxxxxx

...

Read More


text:
Q: How to set/change a cookie via php? I use this code to change the cookie value in php, or set it if it does not exist yet:
setcookie('maintenance_site_contact_failed', '1', time()+3600, '/', 'entwicklung');

And I am using this code to set a cookie in javascript:
setCookie('maintenance_site_contact_failed', '0', 1);

function setCookie(name,value,days)
{
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}

But as you can see in the following screenshot the cookie is created a second time instead of changing the existing one, but the duplicate has a dot in the domain name.

Why is there a dot and why is the cookie created twice?

What I try:
If a user sends my form and the validation fails on serverside, then
I am setting the cookie maintenance_site_contact_failed in the  PHP script to 1 so that the client knows that an error happened.
The javascript then checks the value of the cookie, and if the cookie value is 1 then it shows an error and resets the cookie value to 0.

A: Looks like your cookie is only available to different subdomains because in the php equivalent you're assigning a value for the domain parameter.
Try to do the same inside the Javascript setCookie function:
document.cookie = name + "=" + (value || "") + expires + "; path=/; domain=entwicklung";


text:
Q: Can an ungrounded conductive cavity provide electrostatic shielding? This comes from Electromagnetic Fields and Waves by Lorrain et al, page 77 on a Hollow, ungrounded conductor enclosing a charged body:

The surface charge density at a given point on the outside surface of the conductor is independent of the distribution of Q in the cavity. It is the same as if the conductor were solid and carried a net charge Q.

1) I don't believe this. As I move +Q around the inside of the cavity, this will affect the distribution of $-Q$ on the inside surface, which must also affect $+Q$ on the outside surface to keep $E=0$ inside the cavity conductor.

Inversely, the field inside the cavity is independent of the field outside the conductor. The conductor then acts as an *electrostatic shield.

2) I don't believe this either for similar reasons. The external fields will affect the distribution of $+Q$ on the outer surface, which must affect the distribution of $-Q$ on the inner surface and therefore the electrostatic field inside the cavity, to maintain $E = 0$ inside the conductor.
So am I correct to disbelieve that an ungrounded conductive cavity can provide electrostatic shielding for the reasons 1. and 2. above?

A: These are a little bit tricky and can be confusing, but no, standard E&M is correct on shielding.
1) Electric charges inside a conductor are shielded from the outside. One does this by giving the shield an equal and opposite charge. This charge will rearrange so as to eliminate the field inside the shield (which is conductive). Thus there will be no electric field in the conductor. And since the total assemblage, (shield plus charges) has zero charge, there is no field outside the shield.
2) First consider a solid conductor in the presence of an external charge. You agree that the conductor ends up with a surface charge which cancels the fields inside the shield (otherwise current would flow which is not a static situation). Now imagine hollowing out the conductor. Since the metal you're removing is entirely from regions where there is no electric field, you haven't changed anything. The interior hole will now have no electric field.

A:
As I move +Q around the inside of the cavity, this will affect the distribution of −Q on the inside surface, which must also affect +Q on the outside surface to keep E=0 inside the cavity conductor.

The second "must" is wrong. The change in distribution of the -Q on the inside surface alone will cancel out the electric field generated by the cavity charge +Q out of the inside surface.

The external fields will affect the distribution of +Q on the outer surface, which must affect the distribution of −Q on the inner surface and therefore the electrostatic field inside the cavity, to maintain E=0 inside the conductor.

This "must" is wrong too. The total electric field of cavity charges and the inside surface charges is zero in the area outside of the inside surface, and the total electric field of outside electric field and the outside surface charges is zero inside the outside surface. The result is a net zero field in the intersection of these two area, namely, the area between the inside surface and the outside surface, a.k.a the conductor. These two parts change independently.

A: I answered this question in this European Journal of Physics article from 2016.
https://arxiv.org/abs/1609.04248


text:
Q: How to add preventDefault in a function where event is not the param This is a html part of my angularjs app :
youtube

and in controller :
$rootScope.createTab = function(url) {
    if (isExtension !== undefined) {
        chrome.tabs.create({url: (url)});
    } else {
        e.preventDefault();
        window.open(url,'_blank');
    }
}

How to add the support of preventDefault ? 'e' is not defined, but i need 'e' , and i have already a param to pass... It's a chrome app but it's also available like a mini-website. I want links opened in a new tab, even if we are not on chrome.

A: You can pass in $event from the markup and use it in your handler.
ng-click="createTab('https://www.youtube.com/watch?v=cRa8VRM5d5c', $event);"

And
$rootScope.createTab = function(url, event) {
    event.preventDefault();
    if (isExtension !== undefined) {
        chrome.tabs.create({url: (url)});
    } else {
        e.preventDefault();
        window.open(url,'_blank');
    }
}

$event - Directives like ngClick and ngFocus expose a $event object within the scope of that expression.