text:
Q: How to add local filtering option in basic grid using Ext Js 4.2? I have developed a basic grid using Ext Js 4.2. Here's the output..

Now i wanna add filtering option to the columns in this grid. For example (=, >, <) filtering have to occur.
I have found some source code like  which might work but i am struggling where to add those javascript files. Here's my code:

Ext.define("UserListDemo.view.user.UserGrid", {
    extend: "Ext.grid.Panel",
    alias: "widget.userGrid",
    autoHeight:true,
    style: 'margin-top: 10px;margin-left: 15px;margin-right: 20px;',
    title: 'User List',
    store: 'UserStore',
    name: 'userGrid',
    id: 'userGrid',
    loadMask: true,
    syncRowHeight: true,
    columns:[
    {
        text: 'ID',
        sortable: true,
        dataIndex: 'id',
        locked: true,
        width: 120
    },
    {
        text: 'Name',
        dataIndex: 'name',
        locked: true,
        width: 350
    },
    {
        text: 'Address',
        dataIndex: 'address',
        width: 450
    },
    {
        text: 'Contact',
        dataIndex: 'contact',
        width: 250
    },
    {
        text: 'Telephone',
        dataIndex: 'telephone',
        width: 200
    }

]
});

        <title>User List</title>
        <link href="http://10.11.201.93:81/grid/ext-4.2.1/ext-4.2.1.883/resources/css/ext-all.css"
         rel="stylesheet" type="text/css" />

Could someone help me with the source code of filtering and how to integrate it with my basic grid as well ?

A: Finally I have been able to add filtering option into my basic grid. I am sharing the whole process in brief.
Firstly,we should keep in mind that ExtJs is a MVC(MVCS more precisely) kind of framework. So, any kind of feature (grid filtering, chart etc) we have to add we should follow the MVC architecture first. SO, I have to replace the local-filter.js file to the previous UserModel .
Here's is the Model View Controller ( and Store) architecture for ExtJs. I am sharing my whole project's directory.

So, in fine, I place the source code of local-filter.js in UserModel.js replacing the previous source code.
Secondly, You have to just include ListApp.js in the index.php. Then it will implicitly call all the MVC javascript files it needs. Just like that:-

Finally, any json file in the data folder will show the data in the grid which will be shown as the way you filter the date. In this case grid-filter.json has been used. And, you have to set the directory of data in UserMdel.js like that.

So, following these steps and kind of grid with filtering, charts could be developed using ExtJs.


text:
Q: JavaScript change text anchor link iOS 8.1 I have the following JavaScript, that used to work everywhere, and now works everywhere but iOS 8.1.
Anyone know a solution to get this actually working everywhere again?
Press Me

It simply changes the text color and value when the link is clicked, no biggie, but iOS 8 seems to have broken it.
The link still works, but the text never changes.
If I add a
return false;

At the end of the onclick, the text changes, but obviously the link does not get followed.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compare strings ignoring accented characters I would like to know if there is a method that compares 2 strings and ignores the accents making "noção" equal to "nocao".
it would be something like string1.methodCompareIgnoreAccent(string2);

A: There is no built in method to do this, so you have to build your own:
A part of this is solution is from here :
This first splits all accented characters into their deAccented counterparts followed by their combining diacritics. Then you simply remove all combining diacritics.
Also see https://stackoverflow.com/a/1215117/4095834
And then your equals method will look like this:
import java.text.Normalizer;
import java.text.Normalizer.Form;

public boolean equals(Object o) {
    // Code omitted
    if (yourField.equals(removeAccents(anotherField))) {
        return true;
    }
}

public static String removeAccents(String text) {
    return text == null ? null : Normalizer.normalize(text, Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
}

A: You can use java Collators for comparing the tests ignoring the accent and case, see a simple example:
import java.text.Collator;

/**
 * @author Kennedy
 */
public class SimpleTest
{

  public static void main(String[] args)
  {
    String a = "nocao";
    String b = "noção";

    final Collator instance = Collator.getInstance();

    // This strategy mean it'll ignore the accents and the case
    instance.setStrength(Collator.PRIMARY);

    // Will print 0 because its EQUAL
    System.out.println(instance.compare(a, b));
  }
}

Documentation: JavaDoc
Be aware that this collator also ignores differences in case, i.e. it also treats "NOCAO" as equal to "noção". To create a collator that ignores accent differences but distingishes case, you might be able to use a RuleBasedCollator
Do not confuse Collator.setStrength() with Collator.setDecomposition(). The Collator constants PRIMARY, SECONDARY, TERTIARY and IDENTICAL must only be used with setStrength(), while the constants NO_DECOMPOSITION, CANONICAL_DECOMPOSITION and FULL_DECOMPOSITION must only be used with setDecomposition(). (A previous version of this code mixed this up and only worked because NO_DECOMPOSITION and PRIMARY happen to have the same integer value.)


text:
Q: Question on Empty set and Power set Does set A equal to set B ? where
$$ A= \{ \emptyset, a,b,c \} $$ $$ B=\{ a,b,c \}  $$
second question: I know the order of the elements does not matter in a Set.
But i once read about the order of elements(or subset) matters in some case, and i can't remember what it is.
Some help from you guys would be nice.
Thanks

A: The order of the items in the set does not matter.  So these three sets are equal:
$$B = \{a,b,c\} = \{c,b,a\} = \{b,a,c\}$$
A set may have another set as a member.  So a set containing the empty set and another element is distinct from a set containing just one element.  For example, the $A$ and $B$ in your question are distinct sets.
The order of items in ordered pairs contained in sets matter.  So, the following two sets, $C$ and $D$, are distinct because they contain different ordered pairs.
$$C = \{ (a,b) , (c,d) \} $$
$$D = \{ (b,a) , (d,c) \} $$

A: No. $A$ and $B$ are different as they have three elements in common, but $A$ also has $\emptyset$. You might think it is like adding zero, but it is not. The order matters when you have a Cartesian product or ordered $n$-tuples in general, hence the name.

A: *

*Assuming $a,b,c \not = \emptyset$, we have $A-B=\lbrace \emptyset \rbrace\not =\emptyset,$ so $A\not =B$.

*Perhaps the time you saw that the order was of importance was when studying sequences?

A: *

*If $A=B$, it must satisfy $A⊆B$, and $B⊆A$. In your case, $A$ has an element $∅$ that does not appear in $B$. Therefore, $A⊄B$,  they are not equal~

*Oder matters in Pair Set. For instance $A=${(1,2)} and B={(2,1)}$ $,then$A≠B$ .


text:
Q: How to get user by id in discordjs 12? In the previous version of api I can do that with :
client.fetchUser('myid');

but from the v12 that not work anymore.
So what is the alternatives ?

A: For discordjs 12 you should use client.users.fetch(myId) instead fetchUser.
See in documentation: https://discordjs.guide/additional-info/changes-in-v12.html#fetch


text:
Q: Location and folder name of wp-bakery I wanted to to move and start my wordpress site localy.
I can't recognize wp-bakery folder and actually I don't know is the folder of plugin in plugin folder or inside the theme (I have truemag theme)
Best Regards,
Daryush

A: The normal location for plugins are wp-content/plugins. I guess you can find your plugin files in wp-content/plugins/pluginname

A: WPBakery Page Builder plugin directory is: wp-content/plugins/js_composer


text:
Q: Panda not reading rowspan I'm trying to convert Excel to HTML table using to_html.

I used the syntax:
file=pd.read_excel('Report11.xlsx',header=[0,1,2],columns=[2],inplace=True)
table_heading=file.to_html(classes=('tg',),justify='center')
print(table_heading)

It is displaying table in this format:

I want to remove the Unnamed level and display as rowspan.


text:
Q: i don't know how to fix this Performing Mail merge I'm from Vietnam.
link demo
This is my code in word but it doesn't work
«TableStart:ListChiTieu»
«STT»
«TenChiTieu»
«DonViTinh»
«MucCongBo»
«TableEnd:ListChiTieu»

A: You need to set mail merge fields correctly in word document before do anything.
It doesnt work if you only type <<STT>>. It should be a mail merge field. Then only syncfusion can identify that as mail merge field and do the data binding.
Insert mail merge fields
Then follow example in syncfusion until you get correct results.


text:
Q: Jekyll Now GitHub Pages, Tables don't show up I have a jekyll now website and I'm trying to put in some tables. They appear fine in github but not on the website. Here's a few snippets of table formatting that I've tried with no luck.
| P | Q | P * Q |
| - | - | - |
| T | T | T |
| T | F | F |
| F | T | F |
| F | F | F |

|====+====|
+====|====+
|=========|

|---|---|---|
|a  | b | c|
| 1|2|3|

|---+---+---|
+ :-: |:------| ---:|
| :-: :- -: -
:-: | :-

|-----------------+------------+-----------------+----------------|
| Default aligned |Left aligned| Center aligned  | Right aligned  |
|-----------------|:-----------|:---------------:|---------------:|
| First body part |Second cell | Third cell      | fourth cell    |
| Second line     |foo         | **strong**      | baz            |
| Third line      |quux        | baz             | bar            |
|-----------------+------------+-----------------+----------------|
| Second body     |            |                 |                |
| 2 line          |            |                 |                |
|=================+============+=================+================|
| Footer row      |            |                 |                |
|-----------------+------------+-----------------+----------------|

I'm using default settings with Jekyll Now, so markdown is Kramdown. I saw solutions from other stack overflow posts but they don't appear to work. Is there something wrong with my formatting or do I need to do something else to get it working?
Thanks

A: You need to apply some styling to the tables code, for example to apply the css class tablelines you can use inline attributes {: .tablelines} :

| P | Q | P * Q |
| - | - | - |
| T | T | T |
| T | F | F |
| F | T | F |
| F | F | F |
{: .tablelines}

|---|---|---|
|a  | b | c|
| 1|2|3|
{: .tablelines}

|-----------------+------------+-----------------+----------------|
| Default aligned |Left aligned| Center aligned  | Right aligned  |
|-----------------|:-----------|:---------------:|---------------:|
| First body part |Second cell | Third cell      | fourth cell    |
| Second line     |foo         | **strong**      | baz            |
| Third line      |quux        | baz             | bar            |
|-----------------+------------+-----------------+----------------|
| Second body     |            |                 |                |
| 2 line          |            |                 |                |
|=================+============+=================+================|
| Footer row      |            |                 |                |
|-----------------+------------+-----------------+----------------|
{: .tablelines}

| A simple | table |
| with multiple | lines|
{: .tablelines}

Output using kramdown:

      P
      Q
      P * Q

      T
      T
      T

      T
      F
      F

      F
      T
      F

      F
      F
      F

      a
      b
      c

      1
      2
      3

      Default aligned
      Left aligned
      Center aligned
      Right aligned

      First body part
      Second cell
      Third cell
      fourth cell

      Second line
      foo
      strong
      baz

      Third line
      quux
      baz
      bar

      Second body

      2 line

      Footer row

      A simple
      table

      with multiple
      lines

A: According to this GitHub issue the problem is missing styles for tables. As suggested in the ticket try to add table style from here: https://gist.github.com/andyferra/2554919


text:
Q: How to change JPA / hibernate to delete based on ID instead of object Below is the JPA setup I am using.  I am able to delete objects as expected, however I need to provide an entire object. While I do not mind doing this I do not feel that it is best practice.  Is there a way, similar to the findByProductId(int productsId) function that I can use for deleting product that is a native part of JPA?
DAO
 void delete(Products productToDelete);

DAOimpl
@Transactional
public void  delete(Products productToDelete){
    productsManager.delete(productToDelete);
}

Manager
@Resource
@Transactional(readOnly = true)
public interface ProductsManager extends JpaRepository<Products,Integer> {
    Products findByProductId(int productsId);
    List findAll();
}

Here is the test
@Test
public void delete() throws Exception{
    Products productToCreate = new Products();
    productToCreate.setProductName("Test Product");
    productsDao.createProduct(productToCreate);
    List loaded = productsDao.findAll();
    System.out.println("Product: " + loaded);
    assertNotNull(loaded);
    productsDao.delete(productsDao.getProductsById(1));
    List loadedTwo = productsDao.findAll();
    System.out.println("Product After Del: " + loadedTwo);
    assertEquals(loadedTwo.size(),0);
}

A: As I see, your ProductsManager extends JpaRepository (I guess the one from Spring Data JPA), so it inherits a delete method receiving an id (declared in CrudRepository):
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
    ...
    void delete(ID id);
    ...
}

Just expose that method in your DAO interface.


text:
Q: Fadein Fadeout Effects in Jquery i am using jquery addClass and removeClass function
here is code
<script>
$(document).ready(function() {
    abc();

    function abc() {

        res=randomXToY(1,15,0);
            $('#img' + res).addClass('activeImg');
            setTimeout(function() {removeClassImg(res) },3000);
    }
    function removeClassImg(res) {

            $('#img' + res).removeClass('activeImg');
            abc();

    }
    function randomXToY(minVal,maxVal,floatVal)
    {
        var randVal = minVal+(Math.random()*(maxVal-minVal));
        return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
    }
});
</script>

and css is
.activeImg{
    opacity:1 !important;
}

This is working perfect. but now i want to add fadein and Fadeout effects for this..
I dont have idea how to add Fadein effect to addClass activeimg and fadeout effect in remove class.
Anybody have idea about this
Thanks

A: Try
$('#img' + res).fadeOut().removeClass('activeImg');

and similarly
$('#img' + res).fadeIn().addClass('activeImg');

Is there any specific reason you're using !important? That might override the JQuery from perfoming its effects to your element, so take it off if you can.

A: Use this :
 <script>
 $(document).ready(function() {
abc();

function abc() {

    res=randomXToY(1,15,0);
        $('#img' + res).fadeIn().addClass('activeImg');
        setTimeout(function() {removeClassImg(res) },3000);
}
function removeClassImg(res) {

        $('#img' + res).fadeOut().removeClass('activeImg');
        abc();

}
function randomXToY(minVal,maxVal,floatVal)
{
    var randVal = minVal+(Math.random()*(maxVal-minVal));
    return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}
   });
  </script>

Cheers !


text:
Q: How to make multiple requests using retrofit2 and rxjava2 on android? In my android app, I want to make multiple http requests using retrofit and rxjava to fetch json data. The number of request depends on the user's preferences (1 up to 40). Each request is independent and returns same type. So, i tried to apply the way that is recommended in this question (How to make multiple request and wait until data is come from all the requests in retrofit 2.0 - android) which uses the zip function of rx-java. But i couldn't find a way to get and combine the results of each request. Response type that i used for single request in retrofit was Response<List<NewsItem>> where NewsItem is my custom object. (the response is json array actually but in a single request retrofit automatically handles it and converts it into list of my custom object) What i tried so far is below:
My API Interface
public interface API {

    String BASE_URL = "xxx/";

    @GET("news/{source}")
    Observable<List<NewsItem>> getNews(@Path("source") String source);
}

Viewmodel class to fetch data
public class NewsVM extends AndroidViewModel {

    public NewsVM(Application application){
        super(application);
    }

    private MutableLiveData<List<NewsItem>> newsLiveData;

    public LiveData<List<NewsItem>> getNewsLiveData(ArrayList<String> mySourceList) {

        newsLiveData = new MutableLiveData<>();
        loadNews(mySourceList);

        return newsLiveData;
    }

    private void loadNews(ArrayList<String> mySourceList) {

        Gson gson = new GsonBuilder().setLenient().create();

        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(API.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();

        API api = retrofit.create(API.class);

        //Gathering the requests into list of observables
        List<Observable<?>> requests = new ArrayList<>();
        for(String source: mySourceList){
            requests.add(api.getNews(source));
        }

        // Zip all requests
        Observable.zip(requests, new Function<Object[], List<NewsItem>>() {
            @Override
            public List<NewsItem> apply(Object[] objects) throws Exception {

                // I am not sure about the parameters and return type in here, probably wrong
                return new ArrayList<>();
            }
        })
            .subscribeOn(Schedulers.io())
            .observeOn(Schedulers.newThread())
            .subscribe(
                new Consumer<List<NewsItem>>() {
                    @Override
                    public void accept(List<NewsItem> newsList) throws Exception {

                        Log.d("ONRESPONSE",newsList.toString());
                        newsLiveData.setValue(newsList);
                    }
                },
                new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable e) throws Exception {

                        Log.d("ONFAILURE", e.getMessage());
                    }
                }
        ).dispose();

    }
}

It doesn't give error but doesn't give response also since I couldn't handle the response. Can anybody help me in combining the results of the each request? I've searched all the questions but can't find an example like this.

A: try to use Observable.from(Iterable<? extends T> iterable) (Observable.fromArray() in rx-java2) instead of zip
So you'll have something like:
Observable.from(mySourceList)
    .flatMap(new Func1<String, Observable<List<NewsItem>>>() {
        @Override
           public Observable<List<NewsItem>> call(String source) {
                return api.getNews(source);
            }
        })
        .subscribeOn(Schedulers.io())
        .observeOn(Schedulers.newThread())
        .toList() // This will give you List<List<NewsItem>>
        .map(new Func1<List<List<NewsItem>>, List<NewsItem>>() {
            @Override
            public List<NewsItem> call(List<List<NewsItem>> listOfList) {
                //Merged list of lists to single list using Guava Library
                List<NewsItem> list = Lists.newArrayList(Iterables.concat(listOfList));
                return list;
            }
        })
        .subscribe(new Subscriber<List<NewsItem>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
            }

            @Override
            public void onNext(List<NewsItem> newsList) {
                //Attached the final newslist to livedata
                newsLiveData.setValue(newsList);
            }
        });

EDITED Updated the method

A: Object[] objects is the array of items returned by the requests. Assuming that each of your request returns a List<NewsItem> and you wanted to combine all NewsItem into a single List<NewsItem>, I think you can do something along the lines of:
private void loadNews(ArrayList<String> mySourceList) {
    ...
    // Zip all requests
    Observable.zip(requests, new Function<Object[], List<NewsItem>>() {
        @Override
        public List<NewsItem> apply(Object[] objects) throws Exception {
            List<NewsItem> combinedNewsItems = new ArrayList<>();
            for (Object response : objects) {
                combinedNewsItems.addAll((List<NewsItem>) response);
            }
            return combinedNewsItems;
        }
    })
        .subscribeOn(Schedulers.io())
        ...
}

Be aware of the type casting.

A: If the type of data that you are getting is same List and the requests are multiple then you can use Recursion Method to make 1 to n requests and add data List on every success.


text:
Q: How to downgrade svn working copy with svn version? I have downgrade my svn from version 1.8 to 1.7.9. Now When i type command like:
svn info
svn up

or any other commands it give an error that:
svn: E155021: This client is too old to work with the working copy at
(format 31)

I want use that copy only.How could i resolve this issue. I do not want to new checkout. Is there any solution for it.
Any idea..


text:
Q: How to sync row id of list adapter and cursor I have a database and I populate it in a listview using a list adapter. When I delete any row from the listview, the id of the next row doesnt change. For eg, if I have rows with id from 1 to 8 and i delete the 7th row, the new row id's are 1,2,3,4,5,6,8. But in the database, the row ids are 1,2,3,4,5,6,7.
How can I sync these two so that I can access the correct element from the database using the onclick event of ListView?

A: Your provided information is not clear enough.You are deleting a row of id 7 from list view and your table has both 7 th and 8 th row.so still you have all the information you need.If you delete information from database table too then you will delete the row with id 7.still you don't have any problem.You can access row from table according to your list item id.
So may be you are messing with list item position and list item id.Consider id not the position of the item.

A: Just call the following to update your ListView :
cursor.requery();
adapter.notifyDataSetChanged();


text:
Q: java mail program doesn't send mails anymore I have a java program and it send mails to the users. Since 1 week the mails doesn't been send anymore. I didn't change anything, but now I get this error:
connexion failed: Exception reading response;
  nested exception is:
    javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
Exception in thread "main" java.lang.RuntimeException: javax.mail.MessagingException: Exception reading response;
  nested exception is:
    javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
    at Launcher$Connexion.<init>(Launcher.java:33)
    at Launcher.main(Launcher.java:52)
Caused by: javax.mail.MessagingException: Exception reading response;
  nested exception is:
    javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
    at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1407)
    at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1205)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:322)
    at javax.mail.Service.connect(Service.java:236)
    at javax.mail.Service.connect(Service.java:137)
    at Launcher$Connexion.<init>(Launcher.java:28)

I contacted fastmail (mailing server) and they say that the insecure cert is self-signed, and does not expire until 2021.
So I don't know what the problem is.

A: Please add DH parameter limits to the certificate of target server. Custom DH parameters by using openssl dhparam command should be generated and applied with the SSLCertificateFile directive. Please note that the custom DH parameters with a 1024-bit prime will always have precedence over any of the built-in DH parameters.
You should update your Java version to at least version 8 as the 1024-bit restriction should have been lifted to accept 2048-bit parameters.
Please see: Java: Why does SSL handshake give 'Could not generate DH keypair' exception?


text:
Q: Prevent svg translation of fontawesome I have en issue with angular and font awesome. On first generation of list of icons suddenly all css class based icons are translated to svg. It affects only solid icons. for example :

is translated somehow to
<svg _ngcontent-c16="" class="svg-inline--fa fa-minus-square fa-w-14 fa-2x"
 ng-reflect-ng-class="fas fa-2x fa-minus-square" aria-hidden="true" data-prefix="fas" data-icon="minus-square"
 role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512" data-fa-i2svg="">
    <path fill="currentColor"
      d="M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zM92 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H92z">
    </path>
</svg>

Is there any option which can prevent this situation? Force somehow translation?
It can be problematic. For example I cannot use solid icons :(

A: If you'd like Font Awesome not to automatically replace  tags that look like icons with the corresponding <svg>s, you could change the configuration to disable autoReplaceSvg.
If you're loading via

Or if you're building your own bundle and can access the config from within your own script you could do this:
import fontawesome from '@fortawesome/fontawesome'

fontawesome.config = { autoReplaceSvg: false }

A: I had the same issue, the  icon tag was actually translated to SVG when I inspected the element.
The problem was I was loading fontawesome both via CSS and JS calls. When I removed the call to the JS lib and only called the CSS file, the icons rendered properly.


text:
Q: The procedure entry point could not be located in dynamic link library I have the following error when open my application.

I'm use windows 7 32bit platform, and Qt v5.3.1 with MinGW 4.8.2 - 32bit compiler .
All dll's files with Qt5Core.dll for 5.3.1 version already exists .
I don't know how to solve this problem.

A: Probably you get this error because you use dlls from QtCreator directory which was not compiled with mingw (often QtCreator compiled with Microsoft visual studio on Windows)
You should use dlls from C:\Qt\Qt5.0.1\5.0.1\mingw47_32\bin (for example) .
App which was compiled with mingw needs dll which compiled with mingw too.


text:
Q: Installing an OS onto a disk which has reallocated sectors I have an SSD which SMART says has 7 reallocated sectors. However, SMART also says the disk is OK.
Is it all right to install a new OS on it? I am guessing that it would be fine seeing as the sectors are reallocated, the installer will just not 'see them' and will go ahead with the install, but I want to confirm.


text:
Q: Button Link library in Bintray to jCenter not available Could you please help me how to Link Bintray Library to jCenter.
I research a lot and found that we have to be an OSS or Premium account to Update. I also create an Issue on https://issues.sonatype.org/browse/OSSRH-36683 and also get a response.
I also config the OSS account link into bintray account but couldn't see Link To jCenter button.
Library URL: https://bintray.com/khangtran/maven/preferences-helper
Below a screenshot, could you please take a look and guide me what wrong with my configuration.

A: Finally, I found the problem is my Account is Trial Account, so I delete it and re-create it with the "oss" and then setups project the same with the previous and I can add it to jCenter.


text:
Q: Ninject Binding for Lazy where T's constructor has parameters I have a lazy-loaded object that I would like to create an instance of via Ninject, but it doesn't work.
interface IFoo {
    string GetData();
}

class Foo : IFoo {
    private string _data;
    public Foo(string data) {
        _data = data;
    }
    public string GetData() {
        return _data;
    }
}

class MyModule : NinjectModule {
    public override void Load() {
        Bind<IFoo>.To<Foo>().InTransientScope().WithConstructorArgument("data", "blah");
    }
}

// ...

var kernel = new StandardKernel(new MyModule());
Lazy<Foo> myFoo = kernel.Get<IFoo>();
Console.WriteLine(myFoo.GetData());

// Result:
// MissingMemberException: The lazily-initialized type does not have a public, parameterless constructor.

Its complaining that Foo doesn't have a parameterless constructor, which is true but why does it need one as I've provided NInject with the constructor parameter and it's value.
This works when I use IFoo instead of Lazy<IFoo>... so how do I specify that I want the Lazy-loaded object to also use the parameterised constructor?

A: you cant get a IFoo and assign it to Lazy<IFoo> like you do in
Lazy<Foo> myFoo = kernel.Get<IFoo>();

get a Lazy<IFoo> instead
Lazy<Foo> myFoo = kernel.Get<Lazy<IFoo>>();

This requires Ninject.Extensions.Factory


text:
Q: AWS CDK - How to prevent it from creating a default target group? We need to create an ECS cluster with EC2, and use an existing Application Load Balancer.
After many trials and errors I managed to make it work, however it always create an extra default target group on port 80.
This is the code I have (using Java as per requirements):
        cluster = Cluster.Builder.create(scope, "my-ecs-cluster")
                .vpc(awsNetwork.getVpc())
                .capacity(
                    AddCapacityOptions.builder()
                        .instanceType(new InstanceType("m5n.xlarge"))
                        .minCapacity(1)
                        .maxCapacity(1)
                        .desiredCapacity(1)
                        .associatePublicIpAddress(true)
                        .vpcSubnets(
                            SubnetSelection.builder()
                                .subnetType(SubnetType.PUBLIC)
                                .availabilityZones(Arrays.asList("us-west-2a", "us-west-2c"))
                                .build()
                        )
                    .build()
                ).build();

        taskDefinition = Ec2TaskDefinition.Builder.create(scope, "my-taskDefinition")
            .executionRole(Role.fromRoleArn(scope, "my-exec-role", "role-arn..."))
            .build();

        containerDef = ContainerDefinition.Builder.create(scope, "my-ecs-container")
                .essential(true)
                .memoryLimitMiB(2048)
                .memoryReservationMiB(2048)
                .image(ContainerImage.fromEcrRepository(
                    Repository.fromRepositoryName(scope,
                        "my-ecr",
                        "my-image"
                    ),
                    "latest")
                )
                .taskDefinition(taskDefinition)
                .build();

        containerDef.addPortMappings(PortMapping.builder()
            .hostPort(0)
            .containerPort(443)
            .protocol(Protocol.TCP)
            .build());

        taskDefinition.setDefaultContainer(containerDef);

        ApplicationLoadBalancerLookupOptions balancerLookupOptions = ApplicationLoadBalancerLookupOptions.builder()
            .loadBalancerArn("arn:aws:my-alb-arn")
            .build();

        loadBalancer = ApplicationLoadBalancer.fromLookup(scope, "my-alb", balancerLookupOptions);

        balancedEc2Service = ApplicationLoadBalancedEc2Service.Builder.create(scope, "my-ec2-service")
            .cluster(cluster)
            .desiredCount(1)
            .taskDefinition(taskDefinition)
            .loadBalancer(loadBalancer)
            .cpu(1)
            .memoryLimitMiB(2048)
            .build();

        balancedEc2Service.getService().addPlacementStrategies(PlacementStrategy.spreadAcross("attribute:ecs.availability-zone", "instanceId"));

        HealthCheck healthCheck = HealthCheck.builder()
            .path("/healthCheck")
            .protocol(software.amazon.awscdk.services.elasticloadbalancingv2.Protocol.HTTPS)
            .port("traffic-port")
            .unhealthyThresholdCount(2)
            .interval(Duration.seconds(30))
            .healthyThresholdCount(5)
            .timeout(Duration.seconds(5))
            .build();

        balancedEc2Service.getTargetGroup().setHealthCheck(healthCheck);

        ListenerCertificate listenerCertificate = ListenerCertificate.fromCertificateManager(Certificate.fromCertificateArn(scope, "dis-certificate-1", "arn:aws:acm:us-west-2:245459132561:certificate/d2962594-8a40-4f36-abd4-62a6d91d0250"));

        ApplicationTargetGroup targetGroup = ApplicationTargetGroup.Builder.create(scope, "dis-receiver-targetGroup")
            .protocol(ApplicationProtocol.HTTPS)
            .port(443)
            .healthCheck(healthCheck)
            .vpc(awsNetwork.getVpc())
            .build();

        ApplicationListener.Builder.create(scope, "dis-receiver-listener")
            .loadBalancer(loadBalancer)
            .defaultTargetGroups(Collections.singletonList(targetGroup))
            .protocol(ApplicationProtocol.HTTPS)
            .port(443)
            .certificates(Collections.singletonList(listenerCertificate))
            .build();

        balancedEc2Service.getService().attachToApplicationTargetGroup(targetGroup);

One of the target groups is the one I created in code.
The other one is created automatically, and it points to port 80:

If instead of using balancedEc2Service.getService().attachToApplicationTargetGroup(targetGroup); I set it directly into the service, like:
        balancedEc2Service = ApplicationLoadBalancedEc2Service.Builder.create(scope, "my-ec2-service")
            .cluster(cluster)
            .desiredCount(1)
            .taskDefinition(taskDefinition)
            .loadBalancer(loadBalancer)
            .cpu(1)
            .memoryLimitMiB(2048)
// New code
            .listenerPort(443)
            .protocol(ApplicationProtocol.HTTPS)
            .certificate(myCertificate)
            .domainName(myDomainName)
            .domainZone(myDomainZone)
//
            .build();

It creates only one targetGroup, and it is linked to port 443 on ECS:

However the target group itself is on port 80, and so the application gets timed out:

How can I configure a single target group using HTTPS?


text:
Q: Python 3.4 and AVRO: Unable to convert the simple message in AVRO, based on schema? I am looking to create a avro message for each record (csv) with metadata header i.e. with nested schema.
I am using Python 3.4. I have the required modules i.e. avro-python3 downloaded.
I have the record data in form of csv with its header.
Basically I have the code for creating required message and metadata header.
My AVSC file (Sample only):
Schema: {"name": "person","type": "record","fields": [{"name": "address","type": {"type" : "record","name" : "AddressUSRecord","fields" : [{"name": "streetaddress", "type": "string"},{"name": "city", "type":"string"},{"name": "pin", "type":"long"}]}}]}

My record is also created. (Showing the pretty format of record).

For pin: 123.456 (float value)
However, when I am trying to convert the above record in avro format, based on avsc file mentioned, it fails saying the "Tha datum is not the example of schema".
Code:
import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter
import csv
import json
# header class to give header data. Just simple assignment
from header import Header
# body class to give body, just simple assignment for now.
from pnlData import PnlData
import os
import sys

if __name__ == "__main__":
    schemaFile = "/path/tardisPnl.avsc"
    outFile = "/path/SampleOutLanding.avro"
    schema = avro.schema.Parse(open(schemaFile, "r").read())

    a = Header()
    a.generateMessageId() #Simple text generated for now
    a.generateTimestamp() #Simple number generated for now
    #print(a.__dict__)
    b = PnlData()
    b.generatePnlData() #Simple value assigned as seen in example
    #print(b.__dict__)

    landingMessage = {}
    landingMessage["header"] = a.__dict__
    landingMessage["pnlData"] = b.__dict__

    #print (json.dumps(landingMessage))

    writer = DataFileWriter(open(outFile, "wb"), DatumWriter(), schema)
    try:
        writer.append(landingMessage)
    except Exception as e:
        print('Error: %s ' % (e))

    writer.close()

I have tried to convert the above avro schema to JSON schema, then created sample JSON data based on the schema (online links), to see if my data object is correct. Infact I created my record based on sample data generated based on the schema.
However, when I try to use them and run the code it always fails.
I am not much familiar with AVRO, so need to understand what I am missing here? Why this simple data and schema is not working?

I first tried the following simple records (same sample online tool) and schema, and it works.
Simple avsc:
{"name": "person","type": "record","fields": [{"name": "firstname", "type": "string"},{"name": "lastname", "type": "string"},{"name": "address","type": {"type" : "record","name" : "AddressUSRecord","fields" : [{"name": "streetaddress", "type": "string"},{"name": "city", "type":"string"}]}}]}

Simple Data (Again pretty printed):
{
  "firstname": "ABCDEFGHIJKLMN",
  "lastname": "ABCDEFGHIJKLMNOPQRSTUVWXYZAB",
  "address": {
    "streetaddress": "ABCDEFGHIJKLMN",
    "city": "ABCDEFGHIJKLMNO"
  }
}

If I create the above dict, and pass the same (same code, not changes) to avsc file as above, it works fine.
Only difference in my avsc and (simple) sample avsc is one extra nested attribute, etc. I am unable to find the reason for not working in my slightly complex data.

A: The fastavro library has a validate function that can help with this.
Using the data and schema you provided, it would look like this:
schema = {
   "type":"record",
   "name":"SomeName",
   "doc":"This schema contains the metadata fields wrapped in a header field which follows the official SA MessageHeader schema.",
   "fields":[
      {
         "name":"header",
         "type":{
            "type":"record",
            "name":"MessageHeader",
            "fields":[
               {
                  "name":"messageId",
                  "type":"string"
               },
               {
                  "name":"businessId",
                  "type":"string"
               },
               {
                  "name":"batchId",
                  "type":"string"
               },
               {
                  "name":"sourceSystem",
                  "type":"string"
               },
               {
                  "name":"secondarySourceSystem",
                  "type":"string"
               },
               {
                  "name":"sourceSystemCreationTimestamp",
                  "type":"long"
               },
               {
                  "name":"sentBy",
                  "type":"string"
               },
               {
                  "name":"sentTo",
                  "type":"string"
               },
               {
                  "name":"messageType",
                  "type":"string"
               },
               {
                  "name":"schemaVersion",
                  "type":"string"
               },
               {
                  "name":"processing",
                  "type":"string"
               },
               {
                  "name":"sourceLocation",
                  "type":"string"
               }
            ]
         }
      },
      {
         "name":"pnlData",
         "type":{
            "type":"record",
            "name":"pnlDataDetails",
            "fields":[
               {
                  "name":"granularity",
                  "type":"string"
               },
               {
                  "name":"pnl_type",
                  "type":"string"
               },
               {
                  "name":"pnl_subtype",
                  "type":"string"
               },
               {
                  "name":"date",
                  "type":"int"
               },
               {
                  "name":"book",
                  "type":"string"
               },
               {
                  "name":"currency",
                  "type":"string"
               },
               {
                  "name":"category",
                  "type":"string"
               },
               {
                  "name":"subcategory",
                  "type":"string"
               },
               {
                  "name":"riskcategory",
                  "type":"string"
               },
               {
                  "name":"market_name",
                  "type":"string"
               },
               {
                  "name":"risk_order",
                  "type":"string"
               },
               {
                  "name":"tenor",
                  "type":"string"
               },
               {
                  "name":"product",
                  "type":"string"
               },
               {
                  "name":"trade_id",
                  "type":"string"
               },
               {
                  "name":"pnl_local",
                  "type":"long"
               },
               {
                  "name":"pnl_cde",
                  "type":"long"
               },
               {
                  "name":"pnl_status",
                  "type":"string"
               }
            ]
         }
      }
   ]
}

record = {
    "pnlData": {
        "pnl_cde": 997.8100000024,
        "pnl_status": "locked",
        "granularity": "detailed view",
        "book": "8271",
        "date": 20181130,
        "subcategory": "None",
        "pnl_local": 997.7899999917,
        "pnl_subtype": "Regular",
        "tenor": "None",
        "pnl_type": "Daily",
        "risk_order": "None",
        "market_name": "None",
        "trade_id": "None",
        "category": "None",
        "product": "None",
        "currency": "cad",
        "riskcategory": "None"
    },
    "header": {
        "sentBy": "SYSTEM",
        "businessId": "T1",
        "messageId": "pnl_0001",
        "processing": "RealTime",
        "messageType": "None",
        "sourceLocation": "None",
        "sentTo": "SA",
        "secondarySourceSystem": "None",
        "schemaVersion": "1.6T",
        "sourceSystem": "SYSTEM",
        "sourceSystemCreationTimestamp": 1236472051,
        "batchId": "None"
    }
}

import fastavro

fastavro.validation.validate(record, schema)

The error I get is the following: "SomeName.pnlData.pnlDataDetails.pnl_local is <997.7899999917> of type <class 'float'> expected long"


text:
Q: Git Diff problems after bulk rename I am having a lot of trouble working with my Git history after a bulk rename applied to a large project (slightly under 10,000 files). I have changed the project layout by moving files from Project/src/.... to Project/src/main/java/..... I have also modified some of the moved files in the same commit.
Let's take a look at one such file:
$ git logc PINSSUserPasswordUtil/src/main/java/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java
* commit 6e7a960f99b0e6164d2713a4cbca2107034d8bbd
  Author: moffats <moffats@ec78347f-1a2b-0410-964c-a7254f1fcdc6>
  Date:   Thu Apr 23 21:24:30 2015 +0000

      merge gradle branch to the trunk

Ok, looks like we need to use --follow to tell Git to follow renames:
$ git logc --follow PINSSUserPasswordUtil/src/main/java/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java
...
* commit 6e7a960f99b0e6164d2713a4cbca2107034d8bbd
| Author: moffats <moffats@ec78347f-1a2b-0410-964c-a7254f1fcdc6>
| Date:   Thu Apr 23 21:24:30 2015 +0000
|
|     merge gradle branch to the trunk
|
...
* commit ce0c98d4b78e2f006ead16a030b3c5f0d7ec3ac0
  Author: perches <perches@ec78347f-1a2b-0410-964c-a7254f1fcdc6>
  Date:   Thu Mar 22 21:29:41 2012 +0000

      Updates for JSF 2.0 upgrade

There we go. Now let's compare the two versions:
$ git diff -M -l0 ce0c98d4b78e2f006ead16a030b3c5f0d7ec3ac0..HEAD PINSSUserPasswordUtil/src/main/java/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java
diff --git a/PINSSUserPasswordUtil/src/main/java/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java b/PINSSUserPasswordUtil/src/main/java/
new file mode 100644
index 0000000..acc4d40
--- /dev/null
+++ b/PINSSUserPasswordUtil/src/main/java/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java
@@ -0,0 +1,186 @@
+package ca.gc.agr.pinss.userPasswordUtil;
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Map.Entry;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
... etc ...

Git is clearly not detecting the rename. It's not finding the old location of the file, and telling me that the entire file content was added.
Note that it's comparing the existing file to /dev/null, rather than the old file path, which should be:
PINSSUserPasswordUtil/src/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java

Ok, let's examine what the commit where it was renamed looks like:
$ git show --stat=180 6e7a960f99b0e6164d2713a4cbca2107034d8bbd | grep UserPasswordReseter
 PINSSUserPasswordUtil/src/{ => main/java}/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java               |   10 +-

This looks good, so this is where I am stuck. The only way I can get the diff I need is by explicitly telling Git what the old file path used to be:
$ git diff ce0c98d4b78e2f006ead16a030b3c5f0d7ec3ac0:PINSSUserPasswordUtil/src/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java HEAD:PINSSUserPasswordUtil/src/main/java/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java

-- a/ce0c98d4b78e2f006ead16a030b3c5f0d7ec3ac0:PINSSUserPasswordUtil/src/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java
+++ b/HEAD:PINSSUserPasswordUtil/src/main/java/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java
@@ -29,18 +29,18 @@ public class UserPasswordReseter {
        private static final Log log = LogFactory.getLog(UserPasswordReseter.class);

        private static final String DATASOURCE_BEAN_NAME = "dataSource";
-       private static final String USER_PROPERTIES = "configuration/users.properties";
+       private static final String USER_PROPERTIES = "/users.properties";

And now I get what I want.
So why did my previous 'git diff -M -l0' command not work? I think this problem also causes such tools as EGit in Eclipse and 'git instaweb' not to work anymore, which means that I just lost the ability to access pre-rename history with powerful GUI tools.
I am not sure how I can fix it at this point. Any suggestions would be appreciated.
git version 1.9.1
EDIT: As pointed out in the comments, this command:
git diff -M -l0 ce0c98d4b78e2f006ead16a030b3c5f0d7ec3ac0..HEAD PINSSUserPasswordUtil/src/main/java/ca/gc/agr/pinss/userPasswordUtil/UserPasswordReseter.java

didn't work, b/c we need to run the diff on the whole repository in order for rename detection to work. So a command like this works correctly:
$ git diff -M -l0 ce0c98d4b78e2f006ead16a030b3c5f0d7ec3ac0 HEAD

Of course, now I need to look for the file I am interested in inside the big diff output for the whole commit, but it does save me the trouble of having to type the old and the new paths. Still far from ideal, but better than before.

A: Rename detection is computationally expensive (see next paragraph), so git limits it to whatever you configure.  If you don't configure a particular value, git has built in defaults that have increased over the various releases (was 100, then 200, now 400).
In particular, when comparing any two revisions (or more precisely, two trees), path-names that appear in the "old" tree and not the "new" tree provide source candidate files for renames, and path-names that appear in the "new" tree but not the "old" tree provide destination candidates for renames.  To detect an actual rename, git must compare every possible source against every possible destination.
As far as I know, git does not (currently) have a "renamed directory, tail part of file names are the same" heuristic to reduce the size of the list.  If it did that would help a whole lot here.  Without it, you can try setting the rename limit very high (to as many path names as needed), using the -l option to git diff or the diff.renameLimit configuration variable.  Setting it to an explicit 0 means "unlimited" (which is actually 32767 internally, hence not quite unlimited).


text:
Q: Delete from json file in node I got caught on how to delete an element from my json file in node.
Im displaying all my elements from my json file that i have made like this
var json = require('./test.json');
  app.get('/courses', function(req, res) {
    res.render('courses', {
        title: "Hello",
        name: "Fredrik",
        js: json
    });
});

This below is my test.json file
[
{
"id":1,"courseId":"DT162G","courseName":"Javascript-baserad webbutveckling","coursePeriod":1
},
{
"id":2,"courseId":"IK060G","courseName":"Projektledning","coursePeriod":1
},
{
"id":3,"courseId":"DT071G","courseName":"Programmering i C#.NET","coursePeriod":2
}
]

And now i want to be able to delete singel elements that i have looped through in my view
I made this so far but im stuck. And how should the path be in my view?
 Delete

app.delete('/courses/:id', function(req, res) {
  if(json.length <= req.params.id) {
    res.statusCode = 404;
    return res.send('Error 404: No quote found');
  }

  json.splice(req.params.id, 1);

});

A: I hope this helps
var fs = require('fs');

app.delete('/courses/:id', function(req, res) {
var indexOfCouseInJson = json.map(function(item) { return item.id; }).indexOf(req.params.id); //find the index of :id
  if(indexOfCouseInJson === -1) {
    res.statusCode = 404;
    return res.send('Error 404: No quote found');
  }

  var result = json.splice(indexOfCouseInJson,1);
  fs.writeFile(jsonFilePath, JSON.stringify(result), function(err){
   if(err) throw err;
   res.json(true);
 });

});

A: Why having a json FILE with dynamic data inside? You should use a database (mongodb uses json for example) or you have to store it in another way.
But if you still want to save the data in your file, what you did is correct but after you removed the element you wanted you have to save the file again, I guess.

A: To add on ram's answer, You can use the method readJsonSync as
var YourFile  = Fs.readJsonSync('file.json'); and now do delete YourFile.element; reset your elements as YourFile.id = 23; and in the end do a Fs.writeJsonSync('file.json');


text:
Q: Swift: array is set but is then empty when accessed I have an array which is set once a specific API is called. However when I then try to access this array at a later point it is empty again.
The class in question looks like this:
class SearchableLoginFormField: LoginFormField {

    weak var delegate: PopoverPresentableDelegate?
    var selectedObject: Selectable?
    let popoverType: PopoverType
    var sourceList = [Selectable]() {
        didSet {
            // Field set
        }
    }

    private lazy var selectionPopover: ContainerPopover = {
        let popover = LoginFormPopover(objectSelected: { object in
            self.selectedObject = object
            self.text = object.selectionName
            self.selectionPopover.dismiss(animated: true)
        }, popoverType: self.popoverType)
        return popover
    }()

    init(popoverType: PopoverType, fieldTitle: String, fieldIcon: UIImage?,
         colorScheme: UIColor?, returnAction: (() -> Void)?) {
        self.popoverType = popoverType

        super.init(fieldTitle: fieldTitle, fieldIcon: fieldIcon, colorScheme: colorScheme, returnAction: returnAction)
        configureFormField()
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configureFormField() {
        textDidChangeAction = { [weak self] in
            /// We clear the selectedAirport each time user searches in field so that we know whether we need to trigger shouldEndEditingAction or not
            /// (which we only trigger if user ends action and selectedAirport is nil)
            self?.selectedObject = nil

            self?.configureField(with: I6TextInputKeyboardSettings(
                capitalization: .allCharacters,
                spellCheck: .no
            ))

            guard let self = self else { return }

            self.searchObjects(
                field: self,
                popover: self.selectionPopover,
                sourceList: self.sourceList,
                dataPopover: self.selectionPopover)
        }

        self.shouldEndEditingAction = { [weak self] in
            if self?.selectedObject == nil {
                let filteredText = self?.text.replacingOccurrences(of: "-", with: "") // We remove the "-" if user has entered it so that reg can still be validated
                self?.text = filteredText ?? ""
                self?.verifyFieldInput()
            }
        }
    }

    private func searchObjects<T>(field: I6TextField, popover: ContainerPopover, sourceList: [T], dataPopover: ContainerPopover) {
        if field.text.isEmpty {
            dataPopover.dismiss(animated: true, completion: nil)
        } else {

            let filterCompletion: (Int) -> () = { count in
                dataPopover.sourceView = field

                // Present if needed
                let isPopoverPresented = dataPopover.isVisiblyPresented
                if (!dataPopover.isBeingPresented && !isPopoverPresented && count > 0) {
                    self.delegate?.presentPopover(popover: dataPopover)
                }

                if (isPopoverPresented || dataPopover.isBeingPresented) && count == 0 {
                    dataPopover.dismiss(animated: false, completion: nil)
                }
            }

            dataPopover.filterToSearchTerm(field.text.replacingOccurrences(of: "-", with: ""), objects: sourceList, completion:filterCompletion)
        }
    }

    private func verifyFieldInput() {
        let matchingList = sourceList.filter {
            $0.selectionName.lowercased() == self.text.lowercased()
        }
        if matchingList.count == 1 {
            self.text = matchingList[0].selectionName
            self.selectedObject = matchingList[0]
            self.hasError = false
        } else if matchingList.count > 1 {
            self.errorAlert(errorText: Strings.EHandshake.FlightLookupCustomisable.mulitpleMatches.localizedFormat(""))
        } else if matchingList.isEmpty {
            self.errorAlert(errorText: Strings.EHandshake.FlightLookupCustomisable.noSelectionMatches.localizedFormat(""))
        }
        delegate?.textInputValidated(popover: selectionPopover)
    }
}

The variable I am focussed on is the sourceList var.
Now, in the class where this object is created we declare the SearchableLoginFormField as follows:
lazy var iata: SearchableLoginFormField = {
    let field = SearchableLoginFormField(
        popoverType: .airport,
        fieldTitle: FlightLookupStrings.originAiportCode.localized,
        fieldIcon: UIImage.Login.origin,
        colorScheme: fieldColor,
        returnAction: nil)

    field.delegate = self

    validator.registerField(field, rules: [RequiredRule(message: ValidationStrings.aircraftRegistrationRequired.localized)])
    return field
}()

And then we set the sourceList with the following delegate method:
func airportsSet() {
        iata.sourceList = CoreDataObjectsManager.shared.airportsList
    }

This is called when the airports list is retrieved from an API call.
Break points prove that the sourceList is being set correctly:

*

*airportsSet() delegate method is hit and contains the correct airport list

*didSet method on the SearchableLoginFormField is fired and the sourceList is successfully set to the Airports list

*when we hit the textField delegate method upon editing the field, the sourceList is empty
I tried moving the configureFormField() method into the didSet on the sourceList but I have the same result.

I'm really confused how this seems to be set but then empty again. I'm keeping the breakpoint on the didSet and at no point is it being set to empty by anything else.
The superclass contains the following var:
public var textDidChangeAction: (() -> Void)?

and the following textFieldDelegate method:
 open func textFieldDidChangeSelection(_ textField: UITextField) {
        didChangeSelectionAction?()
    }

So in the configureFormField method we are setting the action of this delegate method accordingly which gets triggered. It is at this point that the sourceList is empty.
The field itself is added in viewDidLoad of the main display viewController as follows:
stackView.add(arrangedSubviews: [number, reg, iata, submitButton, errorLabel])


text:
Q: How do I use npm packages and ES6 features with Django? I am currently building out the front-end of a Django app and I want to use the official material design components.
However, I am running into trouble finding ways to integrate this; I want to be able to import the npm packages directly into javascript files and/or Django templates. Does anyone know how to do this?

A: if you using webpack, you need create correct config (webpack.config.js)
a if you use npm run build need in
output: {
    path: path.resolve(__dirname, './dist'),
    publicPath: '/static/youre-folder/dist/',
    filename: 'build.js'
  }

for example.
And next include this adress '/static/youre-folder/dist/build.js' in template django.


text:
Q: insert "enum Identifier" to complete EnumHeader in selenium cucumber integration scenario I am interested to integrate cucumber in selenium feature file
Feature: Test smoke test of Facebook
Scenario : Test FB with valid credentials

    Given Open browser and start application
    When  I provide valid username and password
    Then user should login to FB

Selenium Code just started
package runner;

import cucumber.api.junit.Cucumber;

public class TestRunner
{
    @RunWith(Cucumber.class){

    }
}

added all Jars as per need

Softwares i  am using

*

*selenium standalone server 3.7.1

*testng

*cucumber

*eclipse oxygen

A: Change the runner code to below :
@RunWith(Cucumber.class)
@CucumberOptions(plugin ="", glue="",features="") //Add the values as per ur code structure
public class TestRunner
{

}

A: I misplaced  @RunWith(Cucumber.class) statement
Now its working fine
package runner;
import org.junit.runner.RunWith;
import cucumber.api.junit.Cucumber;

// it need here only ..
@RunWith(Cucumber.class)
public class TestRunner
{
    //  i added here by mistake
}


text:
Q: Is it safe to send username/password in the clear? My website is creating an app that extends its functionality - which means that the app doesn't need to follow a strict OAuth process, since we clearly trust ourselves.
We'd like the user of the app to be able to enter their username and password from within the app...which means  we need a way to transport that info to the webserver to validate them.
Assuming we are using SSL, is this a safe idea?
Do we need to take extra steps, and do we need to somehow insure that the request is coming from our app, and not a spoofed app, or something?

A: Firstly, trusting yourselves is not enough. You will have no control of your app, the device on which its used or the network it's connected to once it's in the hands of your users.
A scheme where you would have a common shared key within your app which only your server would be able to decipher (as alluded in comments) could still cause problems, because users who get hold of your application could possibly reverse-engineer it and obtain that key to target other users.
If you're not using Single-Sign On (SSO) for authenticating to your website, but use plain usernames and passwords in a form, transmitting that over an SSL/TLS connection from your application will be no different from doing so from a browser (over HTTPS), provided that the overall configuration is correct. This is already what happens when you post a form from a browser anyway.
By using SSL/TLS as you suggest, you're actually not sending your password in clear (provided it's configured properly).
Checking whether it comes from your application or a spoofed app is a different matter, which is very difficult to protect against in general. If your service is well-designed, it's often not worth it when you already have user authentication anyway. Authenticated users should only be able to perform actions your server allows them to do, whether the request for those actions come from your app or another app controlled by these users (as long as the server verifies they are authenticated correctly). (Spoof apps tend to be more of a problem for the users themselves, if they are tricked into using them, rather than the service itself in this case.)

A: There are several possible security threats, any of which you can decide whether or not you want to worry about: http://xkcd.com/538/
But the security's original sin is "password in the clear". At least hash it so that it's not stored in the clear on the server.


text:
Q: How to fix libmpfr.so.4 missing? I am trying to compile the code below:
#include"header.h"
int main()
{
char dateString[20], timeString[20];
struct tm *tmptr;
time_t t;
t = time(NULL);
tmptr = localtime(NULL);
printf("%d ---%s\n",tmptr,tmptr);
return 0;
}

Header.h has :
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdarg.h>
#include<time.h>
#include<utime.h>
#include<sys/timeb.h>

When compiling this code, I get an error saying that:
/usr/lib/gcc/i686-linux-gnu/5/cc1: error while loading shared libraries: libmpfr.so.4: cannot open shared object file: No such file or directory

Concluding that it is trying to tell me that, the library file is missing, I went through the previous threads and tried updating gcc compiler but I still see this error. Can somebody please help me to fix it?

A: That file is provided by the libmpfr4 package, which can be installed by opening a terminal (press Ctrl+Alt+T) and running:
sudo apt-get update
sudo apt-get install libmpfr4

If it says the package is already installed, you can try:
sudo apt-get install --reinstall libmpfr4


text:
Q: get the value of dropdown select options using ajax i am stuck,the select options value is sent but it sets the value to 0 all the time i execute the query. how can i get the value of the options to be grabbed ? i would be very grateful for the answer. thanks
here is the form for the select options
            <select name="user_role" id="#user_role">
                <option>
                </option>
                <option value="1">
                    Super Admin
                </option>
                <option value="2">
                    Team Manager
                </option>
                <option value="3">
                    Staff
                </option>
            </select>

the ajax function i set is
$(".save-update").click(function(e) {
                        e.preventDefault();
                        //alert("save button clicked");
                        var username = $("#username").val();
                        var email = $("#email").val();
                        var user_role = $("#user_role option:selected").val();
                        $.post("../lib/ajax/edit-user-save.php",{username:username,email:email,id:id,user_role:user_role},function(data){
                                //alert(data);
                                $(".save-update").parent().parent().addClass("table-list");
                                $(".save-update").parent().parent().replaceWith(data);
                                });

                });

now, the edit-user-save.php where the query is done
if(isset($_POST['user_role'])){
            $user_role = $_POST['user_role'];
            //echo $id;
        }

    //$query = mysql_query();
    $query = mysql_query("UPDATE users SET username='$username', email='$email',user_role='$user_role' WHERE id=$id");
    if(!$query){
            echo "could not update the table".mysql_error();
        }

A: oh i got the answer, so stupid of me
id="#user_role"
i wrote # at the id .. haha ... !

A: Your ID is not correct in HTML, change this
id="#user_role"

to this
id="user_role"

A: Replace
 id="#user_role">

with
 id="user_role">


text:
Q: MySQL re-order row priority field values and also make them sequential Given the following table:
+--------+-------------------+-----------+
| ID     | Name              |  Priority |
+--------+-------------------+-----------+
| 1      | Andy              | 1         |
| 2      | Bob               | 2         |
| 3      | David             | 8         |
| 4      | Edward            | 9         |
| 5      | CHARLES           | 15        |
+--------+-------------------+-----------+

I would like to move CHARLES to between Bob and David by Priority value (ignore the alphabetical list, this is just to make the desired result obvious).
(Also note the Priority values may not be sequential)
To do this I need to change CHARLES' current Priority (15) to Bob's Priority+1, and update David and Edward's Priority to Priority+1.
I can DO this if I know two things, the id of CHARLES and the Priority value of the row he must be after (Bob):
UPDATE mytable SET Priority =
IF(ID = :charles_id, :bob_priority + 1,
IF(Priority >= :bob_priority,
Priority + 1, Priority))

The PROBLEM or at least question is, how could I compress the resulting values to 1,2,3,4,5 instead of 1,2,3,9,10 - and do it in one shot?
Oracle has a "pseudo field" which is the index of the row, but I don't know of anything equivalent in MySQL.

A: The first part of the problem is fairly trivial...
DROP TABLE IF EXISTS priorities;

CREATE TABLE priorities
(ID SERIAL PRIMARY KEY
,Name VARCHAR(12) NOT NULL
,Priority INT NOT NULL
,INDEX(priority)
);

INSERT INTO priorities VALUES
(101,'Andy',1),
(108,'Bob',2),
(113,'David',8),
(124,'Edward',9),
(155,'CHARLES',15);

UPDATE priorities a
  JOIN
     ( SELECT x.id,x.name, @i:=@i+1 priority FROM priorities x, (SELECT @i:=0) vars ORDER BY id) b
    ON b.id = a.id
   SET a.priority = b.priority;

SELECT * FROM priorities
+-----+---------+----------+
| ID  | Name    | Priority |
+-----+---------+----------+
| 101 | Andy    |        1 |
| 108 | Bob     |        2 |
| 113 | David   |        3 |
| 124 | Edward  |        4 |
| 155 | CHARLES |        5 |
+-----+---------+----------+


text:
Q: Dyck path bijection The problem is as below:
Prove that there is a bijection between Dyck paths from $(0, 0)$ to $(2n, 0)$ and $n$-tuples $(a_1, a_2, a_3, ... a_n)$ of integers $a_i \geq 2$ such that in the sequence $1a_1a_2...a_n1$, each $a_i$ divides the sum of its neighbors.
Below is the progress we have made:
Let $D^n$ be the set of Dyck paths from $(0, 0)$ to $(2n, 0)$.
$$\text{Let }G^n=\bigg\{g = g_1g_2...g_n\ :\ g_i \in \mathbb{N},\ \sum_{i = 1}^n{g_i}=n,\ \sum_{i = 1}^n{g_i - 1}=0,\ \forall\ k < n \in \mathbb{N}, \sum_{i = 1}^k{g_i - 1} \ge 0\bigg\}$$
Let $S^n$ be the set of $n$-tuples $(a_1, a_2, a_3, ... a_n)$ of integers $a_i \geq 2$ such that in the sequence $1a_1a_2...a_n1$, each $a_i$ divides the sum of its neighbors.
Define $g: D^n \longrightarrow G^n, g(d) = b_1b_2...b_n$, where $b_i$ is the number of times path $d$ moves up between the $(i-1)$th and the $i$th time the path moves down. Note that $b_1$ is the number of times the path moves up before the first time it moves down.
$$\text{Define } h: \mathbb{N} \times \mathbb{N} \longrightarrow \mathbb{N}, h(a, b) = \begin{cases}
b - a & b > a\\
\lceil\frac{a}{b}\rceil \cdot b - a & b \leq a
\end{cases}$$
Define $f : G^n \longrightarrow S^n$. Note that while not part of $f(d)$, if used, $s_{-1} = 0$ and $s_0=1$.
        $$f(v) = (s_1, s_2, s_3, ... s_n), s_i = h(s_{i - 2}, s_{i - 1})+s_{i-1}\cdot v_i$$
Example:
Consider the example of the following Dyck path: $\{(0, 0), (1, 1), (2, 2), (3, 1), (4, 2), (5, 1), (6, 0)\}$.
We begin by calculating $v = g(d)$ to be $(2, 1, 0)$, since the path moves upwards twice before it moves down first, then it moves up once before moving down again, and ends by moving down without moving up at all. We can see that $\sum v_i = 3 = n$ and that $\sum v_i - 1 = 0$, with every sum along the way non-negative as well, confirming that $v \in G^3$.
Then we begin calculating $s = f(v)$ with $s_1 = h(s_{-1}, s_{0}) + s_{0} \cdot v_1 = h(0, 1) + v_1 = 1 + 2 = 3$. Then we calculate $s_2 = h(s_0, s_1) + s_1 \cdot v_2 = h(1, 3) + 3 \cdot 1 = 2 + 3 = 5$. Finally, we calculate $s_3 = h(s_1, s_2) + s_2 \cdot v_3 = h(3, 5) + 5 \cdot 0 = 2 + 0 = 2$. Therefore we have that the sequence is $13521$, with $(s_1, s_2, s_3) = (3, 5, 2)$
Now, the problem that I have is to prove that $f$ is onto. With the definition of $f$ and $s=(s_1, s_2, ..., s_n)$ known, it is easy to express $v_i =\frac{s_i - h(s_{i - 2}, s_{i-1})}{s_{i-1}}$.  However, I don't know how to prove that $v=(v_1, v_2, ..., v_n)$ $\in G$. That is, $v$ has to satisfy two properties:
$1. \sum_{i = 1}^n{v_i - 1}=0,$
$2. for \ all\ k < n \in \mathbb{N}, \sum_{i = 1}^k{v_i - 1} \ge 0$
Can anybody provide some help or give some hints? Thanks in advance!


text:
Q: Open a link in browser from winforms gridview column I am new to winforms.I cannot post any code as I am using a designer for my gridview in winforms. I have 2 columns. In 1 column links name is there and other column which is hidden has link names actual link. E.g if in column 1 Google is written so, there is 2nd column(hidden) which has http://www.google.com in it. When I click the datagridview cell with links name, the link should open in browser. Is there a way to do it. I googled it but all I got is
this. Please help.

A: All you need to do is to add an OnClick handler to your row and from there start a new process which will launch a browser with the url:
private void OnClick(object sender, RowEventArgs e) // I don't know exactly how the event handlers signature is
{
    // Get the url from the row
    var url = e.Row.Columns[1].Value;
    Process.Start(url);
}

EDIT
The code above will start the default browser. If you want to start a non-default browser i.e. IE (pun intended) you'll have to use an overload of Process.Start and pass it the path to executable and the url like this:
Process.Start("iexplore.exe", url);


text:
Q: Records where value is not equal to current value I have 7 Departments and an Employee that is assigned to 2 of them through a polymorphic join model called DepartmentItem. When I run the following I expect to get 5 records that the employee does not belong to, but instead I get all 7.
$employee = \App\Employee::find(1);
$departments = \App\Department::join('department_items', 'department_items.department_id', '=', 'departments.id')
    ->select('departments.*')
    ->groupBy('departments.id')
    ->where('company_id', $employee->company_id)
    ->where('department_items.item_id', '!=', $employee->id)
    ->where('department_items.item_type', 'employee')
    ->get();
dd($departments);

This returns 7 departments when it should only return 5. When I change '!=' to '=' it returns the 2 departments that the employee is assigned to.
Here are the model relations:
// Company
public function departments() {
    return $this->hasMany(Department::class);
}
public function employees() {
    return $this->hasMany(Employee::class);
}

// Department
public function company() {
    return $this->belongsTo(Company::class);
}
public function employees() {
    return $this->morphedByMany(Employee::class, 'item', 'department_items');
}

// DepartmentItem
public function department() {
    return $this->belongsTo(Department::class);
}
public function item() {
    return $this->morphTo();
}

// Employee
public function company() {
    return $this->belongsTo(Company::class);
}

A: You should use <> instead of != as where clause method takes mysql operators.
So your code should be like this:
$departments = \App\Department::join('department_items', 'department_items.department_id', '=', 'departments.id')
    ->select('departments.*')
    ->groupBy('departments.id')
    ->where('company_id', $employee->company_id)
    ->where('department_items.item_id', '<>', $employee->id)
    ->where('department_items.item_type', 'employee')
    ->get();

Hope this helps!


text:
Q: Minimal, good-citizen, C# console application boilerplate What would be the minimal boilerplate code for a C# console application entry-point that would make it a well-behaved citizen?
When anyone goes out to create a Console Application project using Visual Studio (up to 2008 at the time of writing), you are presented with a boilerplate Program.cs that looks like this:
class Program
{
    static void Main(string[] args)
    {
    }
}

There are, however, a few things that everyone needs to do to make a console application a minimally good citizen. For example, if an exception occurs, then write out a clean message to standard error (Console.Error) and not standard output (Console.Out). Likewise, set the error code to a non-zero value in the event of some error so that calling processes can detect failures.
What would be the minimal boilerplate code for a C# console application entry-point that would make it a well-behaved citizen? What would you add or change to the following?
using System;
using System.Diagnostics;
using System.Linq;

static class Program
{
    static void Run(string[] args)
    {
        // TODO Replace line-echoing sample with actual application code

        string line;
        while ((line = Console.ReadLine()) != null)
            Console.WriteLine(line);
    }

    static int Main(string[] args)
    {
        // TODO Use a more robust arguments parser
        if (args.Any(arg => arg.Equals("/v") || arg.Equals("-v"))) // verbose?
            Trace.Listeners.Add(new ConsoleTraceListener(true));

        try
        {
            Run(args);
            return Environment.ExitCode;
        }
        catch (Exception e)
        {
            Console.Error.WriteLine(e.Message);
            Trace.TraceError(e.ToString());

            return Environment.ExitCode != 0
                 ? Environment.ExitCode : 100;
        }
    }
}

What this boilerplate achieves:

*

*If an exception is thrown:

*

*a clean message is printed to standard error

*the full details are traced

*the exit code is set to an arbitrary non-zero value (100) unless already set

*Tracing can be turned on dynamically via a verbose switch

*Tracing is sent to standard error to not interfere with the real output

*On successful completion, the exit code reflects the last Environment.ExitCode value, which is usually zero but can be changed by downstream code

*Program class is static

Non-goals of this question:

*

*Identify command-line arguments handling code or library

*Identify an external logging or tracing library

A: I think all depends on actual requirements for that app. If there is no requirement to do custom error handling - don't do that. If no program needs to check your app's exit code - no need to return it; and I believe there are cases where those requirements do not apply.
In other words, minimal is minimal; do the simplest thing that could possibly work. And if yor app meets requirements, I guess we can call it well-behaved.

A: To me I would want to see Run(args) replaced with the instantiation of a class.  Something like:
Main Try:
try
{
    // Process args to get parameters for AClass
    AClass program = new AClass(a, b);
    return program.Run();
}

AClass:
public class AClass {
    AClass(string a, string b) { ... }
    public int Run() {
        ...
        return Environment.ExitCode;
    }
}

Something like this is going to discourage procedural code and encourage creating an object oriented approach.
In regards to the AClass() constructor, I think the arguments should be processed prior to being passed into AClass() instead of AClass() having to know that it's created via a Console app.

A: On this subject, I have found this article to be the most in depth and informative:
Console Appplications in .NET, or Teaching a New Dog Old Tricks
Michael Brook
MSDN Magazine Feb 2004
http://msdn.microsoft.com/en-us/magazine/cc164014.aspx

A: I use emacs, and a thing called defaultcontent.el  .  If you aren't familiar, Emacs is a text editor, and is very extensible.  defaultcontent.el is an extension that inserts (surprise) default content into new files, when they are first created by emacs.
So if I try to open a .cs file that does not exist, emacs creates it, and then puts a bunch of default content into it.  I decide what content to include in new files. For my C# files, this content includes:

*

*simple documentation with the timestamp, copyright, other boilerplate.

*a bunch of assembly-scope attributes (FileVersion, AssemblyDescription, etc)

*a single class

*a contructor that accepts an array of string arguments, and parses them; the parse logic is a switch statement, with some boilerplate for parsing integers, strings, and booleans.

*a Usage method, that prints the usage information.

*a Main method, which instantiates the class and calls "Run()"; this is surrounded in a try..catch and in the catch, the Usage() method is called.  If any error occurs anywhere in the program, the usage message is displayed.

The defaultcontent.el also lets me position the cursor where I want.  In my case, that's in the middle of the empty Run() method.
This is my default content:
// default.cs
// ------------------------------------------------------------------
//
// Description goes here....
//
// Author: MyUser
// built on host: MyMachine
// Created Tue Oct 27 15:01:18 2009
//
// last saved:
// Time-stamp: <2009-October-20 00:18:52>
// ------------------------------------------------------------------
//
// Copyright Notice here
// All rights reserved!
//
// ------------------------------------------------------------------

using System;
using System.Reflection;

// to allow fast ngen
[assembly: AssemblyTitle("default.cs")]
[assembly: AssemblyDescription("insert purpose here")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Dino Chiesa")]
[assembly: AssemblyProduct("Tools")]
[assembly: AssemblyCopyright("Copyright notice again")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("1.1.1.1")]

namespace Cheeso.ToolsAndTests
{

  public class default
  {
    // ctor
    public default () {}

    string _positionalParam1;
    string _param1;
    int _intParam = DefaultIntParamValue;
    bool _flag1;

    private readonly int DefaultIntParamValue = -99;

    // ctor
    public default (string[] args)
    {
        for (int i=0; i < args.Length; i++)
        {
            switch (args[i])
            {
            case "-stringArg":
                i++;
                if (args.Length <= i) throw new ArgumentException(args[i]);
                _param1 = args[i];
                break;

            case "-intArg":
                i++;
                if (args.Length <= i) throw new ArgumentException(args[i]);
                if (_intParam != DefaultIntParamValue)
                    throw new ArgumentException(args[i]);
                if (args[i].StartsWith("0x"))
                    _intParam = System.Int32.Parse(args[i].Substring(2), System.Globalization.NumberStyles.AllowHexSpecifier );
                else
                    _intParam = System.Int32.Parse(args[i]);
                break;

            case "-boolarg":
                _flag1 = true;
                break;

            case "-?":
                throw new ArgumentException(args[i]);

            default:
                if (_positionalParam1 != null)
                    throw new ArgumentException(args[i]);

                _positionalParam1 = args[i];
                break;
            }
        }

        // default values
        if (_positionalParam1 == null)
            _positionalParam1 = "default.value.for.positional.param";

        if (_param1 == null)
            _param1 = "default.value.for.param1";

        if (_param2 == 0)
            _param2 = DEFAULT_value_for_param2;

    }

    public void Run()
    {

    }

    public static void Usage()
    {
        Console.WriteLine("\ndefault: <usage statement here>.\n");
        Console.WriteLine("Usage:\n  default [-arg1 <value>] [-arg2]");
    }

    public static void Main(string[] args)
    {
      try
      {
        new default(args)
            .Run();
      }
      catch (System.Exception exc1)
      {
        Console.WriteLine("Exception: {0}", exc1.ToString());
        Usage();
      }
    }

  }
}

I also have defaultcontent set up for .c, .cpp, .vb, .csproj, .xml, .xsd, .wsdl, makefile, and many other file types.


text:
Q: .Net System.OutOfMemoryException filling a datatable I need to extract data from a .dbf file and transform it into xml.  I wrote a routine that does it just fine.  However now we are encountering very large .dbf files - like 2GB +.  And this code throws an OutOfMemoryException on those files.
Public Function GetData() As DataTable
    Dim dt As New DataTable(Name)
    Dim sqlcommand As String= "Select * From MyTable"
    Dim cn As New OleDbConnection(myconnectionstring)

    Try
        cn.Open()
        Dim cmd As New OleDbCommand(sqlcommand, cn)
        dt.Load(cmd.ExecuteReader())
    Catch ex As Exception
        Throw ex
    Finally
        dt.Dispose()
        cn.Close()
        cn.Dispose()
    End Try
    Return dt

The thing is - if I run this same code on my computer through Visual Studio in debug mode against the same 2GB .dbf file no exception is thrown.  It's almost like Visual Studio manages the memory differently then the app does alone.
Is there anyway to get around the memory issues?  I've tried using a DataAdapter with similar results.  Is this behavior I am seeing with Visual Studio expected/by design?

A: A datatable is in memory, so it will fail on large files or go very slow depending on the size of the file.
You'll need to use a SqlDataReader to read the data record by record and an XmlWriter to create your XML file.
Something like this (Code not checked)
Public Sub WriteToXml(Dim xmlFileName As String, Dim connectionString)
    Dim writer As XmlWriter
    writer = XmlWriter.Create(xmlFileName)
    Dim commandText As String= "Select * From MyTable"
    Dim connection As New OleDbConnection(connectionString)

    Try
        connection.Open()
        Dim command As New OleDbCommand(commandText, connection)
        Dim reader As SqlDataReader
        reader = myCommand.ExecuteReader()

        While reader.Read()
            write.WriteRaw("xml")
        End While
    Catch ex As Exception
        Throw ex
    Finally
        connection.Close()
        connection.Dispose()
    End Try
End Sub

A: In no way you can load an entire 2GB database in memory. You will need to load and process the database records in chunks
To make the partial loading of the database, you can use for example the TOP and ROWNUM clauses in the SELECT command. Look at the documentation of SQL Server for more details.

A: If you want to process large files, think about DataReader without filling DataSet; it won't load the whole table in memory, but go row-by-row. And also use SqlDataAdapter.Fill() instead of this way, don't forget to Dispose it.
Dim conn As New SqlConnection(connection)
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = new SqlCommand(query, conn)
adapter.Fill(dataset)
adapter.Dispose()
conn.Dispose()

You don't really need to call .Close() for connection, as it's called when you call .Dispose().
PS: You don't close Reader, probably that's why. Yes, VS.NET will close it faster than GC.

A: Why not do something simple like:
using (var writer = CreateXmlWriter(fileName))
{
  while (reader.Read())
  {
    var value = new ObjectFromDatabaseReader(reader);
    value.WriteXml(writer);
  }
}

This will just stream the data in a row at a time, convert to an object and then save as xml. This will hardly use any memory at all and should be very fast.


text:
Q: Maya Python scale picture How to scale a picture to fit a window/layout?

With the code below the original image is not actually enlarged to 300px, it is displayed with the original image size instead.
import maya.cmds as cmds

if (cmds.window(window1, exists=True)):
    cmds.deleteUI(window1)

window1 = cmds.window(w=300, h=300)
layout = cmds.columnLayout(w=300, h=300)
cmds.picture( image='image.png', w=300, h=300)

cmds.showWindow( window1 )

A: Try this
import maya.OpenMaya as om

def resize_image(source_image, output_image, width, height):

    image = om.MImage()
    image.readFromFile(source_image)

    image.resize( width, height )
    image.writeToFile(output_image, 'png')

resizeImage('<source_image.png>','<output_image.png>', 300, 300)

A: I have used iconTextButton to set an image with different width and height.
Use adjustableColumn=False to set width/height of your image.
You can also try iconTextStaticLabel cmd.
Hope this will work for you..
import maya.cmds as cmds

if cmds.window('Test',exists=True):
   cmds.deleteUI('Test')

cmds.window('Test',title='Test Image', bgc=[0.266, 0.266, 0.266], widthHeight=[600,400], sizeable = True)
parentLayout = cmds.columnLayout(adjustableColumn=False)
cmds.iconTextButton(style="iconOnly",image1='Capture.png',p=parentLayout,w=150,h=150)
cmds.setParent('..')
cmds.showWindow('Test')


text:
Q: URL Encode a string in jQuery for an AJAX request I'm implementing Google's Instant Search in my application. I'd like to fire off HTTP requests as the user types in the text input. The only problem I'm having is that when the user gets to a space in between first and last names, the space is not encoded as a +, thus breaking the search. How can I either replace the space with a +, or just safely URL Encode the string?
$("#search").keypress(function(){
    var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val();
    var options = {};
    $("#results").html(ajax_load).load(query);
});

A: Try encodeURIComponent.

Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).

Example:
var encoded = encodeURIComponent(str);

A: I'm using MVC3/EntityFramework as back-end, the front-end consumes all of my project controllers via jquery, posting directly (using $.post) doesnt requires the data encription, when you pass params directly other than URL hardcoded.
I already tested several chars i even sent an URL(this one http://www.ihackforfun.eu/index.php?title=update-on-url-crazy&more=1&c=1&tb=1&pb=1) as a parameter and had no issue at all even though encodeURIComponent works great when you pass all data in within the URL (hardcoded)
Hardcoded URL i.e.>
 var encodedName = encodeURIComponent(name);
 var url = "ControllerName/ActionName/" + encodedName + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;; // + name + "/" + keyword + "/" + description + "/" + linkUrl + "/" + includeMetrics + "/" + typeTask + "/" + project + "/" + userCreated + "/" + userModified + "/" + status + "/" + parent;

Otherwise dont use encodeURIComponent and instead try passing params in within the ajax post method
 var url = "ControllerName/ActionName/";
 $.post(url,
        { name: nameVal, fkKeyword: keyword, description: descriptionVal, linkUrl: linkUrlVal, includeMetrics: includeMetricsVal, FKTypeTask: typeTask, FKProject: project, FKUserCreated: userCreated, FKUserModified: userModified, FKStatus: status, FKParent: parent },
 function (data) {.......});

A: encodeURIComponent works fine for me. we can give the url like this in ajax call.The code shown below:
  $.ajax({
    cache: false,
    type: "POST",
    url: "http://atandra.mivamerchantdev.com//mm5/json.mvc?Store_Code=ATA&Function=Module&Module_Code=thub_connector&Module_Function=THUB_Request",
    data: "strChannelName=" + $('#txtupdstorename').val() + "&ServiceUrl=" + encodeURIComponent($('#txtupdserviceurl').val()),
    dataType: "HTML",
    success: function (data) {
    },
    error: function (xhr, ajaxOptions, thrownError) {
    }
  });

A: Better way:
encodeURIComponent escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
To avoid unexpected requests to the server, you should call encodeURIComponent on any user-entered parameters that will be passed as part of a URI. For example, a user could type "Thyme &time=again" for a variable comment. Not using encodeURIComponent on this variable will give comment=Thyme%20&time=again. Note that the ampersand and the equal sign mark a new key and value pair. So instead of having a POST comment key equal to "Thyme &time=again", you have two POST keys, one equal to "Thyme " and another (time) equal to again.
For application/x-www-form-urlencoded (POST), per http://www.w3.org/TR/html401/interac...m-content-type, spaces are to be replaced by '+', so one may wish to follow a encodeURIComponent replacement with an additional replacement of "%20" with "+".
If one wishes to be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent (str) {
  return encodeURIComponent(str).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
}

A: use jQuery.param().....
Description: Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.

A: try this one
var query = "{% url accounts.views.instasearch  %}?q=" + $('#tags').val().replace(/ /g, '+');


text:
Q: Getting Detail Information of process handle I have run "handle.exe -a \Device\0000006c" on command line where "\Device\0000006c" is physical object name of my device for e.g.. Microphone and getting following output:
Handle v4.0
Copyright (C) 1997-2014 Mark Russinovich
Sysinternals - www.sysinternals.com

svchost.exe        pid: 864    type: File           770: \Device\0000006c\global
svchost.exe        pid: 864    type: File           ECC: \Device\0000006c\global
svchost.exe        pid: 348    type: File           514: \Device\0000006c\global
svchost.exe        pid: 348    type: File           88C: \Device\0000006c\global
audiodg.exe        pid: 4592   type: File           1C4: \Device\0000006c
audiodg.exe        pid: 4592   type: File           1CC: \Device\0000006c

Last two line of output showing that device is being used by audiodg.exe process when audio is being played.
audiodg.exe        pid: 4592   type: File           1CC: \Device\0000006c

I am able to get that "1CC" is handle Hex Address but what is "\Device\0000006c" here is it name associated with handle or something else being searched in core of handle.
I am trying to get handle information from this below link
https://code.msdn.microsoft.com/windowsapps/CppFileHandle-03c8ea0b
but not able to get this kind of information for handle
DWORD EnumerateFileHandles(ULONG pid)
{
    HINSTANCE hNtDll = LoadLibrary(_T("ntdll.dll"));
assert(hNtDll != NULL);

PFN_NTQUERYSYSTEMINFORMATION NtQuerySystemInformation =
    (PFN_NTQUERYSYSTEMINFORMATION)GetProcAddress(hNtDll,
    "NtQuerySystemInformation");
assert(NtQuerySystemInformation != NULL);

PFN_NTQUERYINFORMATIONFILE NtQueryInformationFile =
    (PFN_NTQUERYINFORMATIONFILE)GetProcAddress(hNtDll,
    "NtQueryInformationFile");

DWORD nSize = 4096, nReturn;
PSYSTEM_HANDLE_INFORMATION pSysHandleInfo = (PSYSTEM_HANDLE_INFORMATION)
    HeapAlloc(GetProcessHeap(), 0, nSize);

while (NtQuerySystemInformation(SystemHandleInformation, pSysHandleInfo,
    nSize, &nReturn) == STATUS_INFO_LENGTH_MISMATCH)
{
    HeapFree(GetProcessHeap(), 0, pSysHandleInfo);
    nSize += 4096;
    pSysHandleInfo = (SYSTEM_HANDLE_INFORMATION*)HeapAlloc(
        GetProcessHeap(), 0, nSize);
}
DWORD dwFiles = 0;

HANDLE hProcess = OpenProcess(
    PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (hProcess == NULL)
{
    _tprintf(_T("OpenProcess failed w/err 0x%08lx\n"), GetLastError());
    getchar();
    return -1;
}

for (ULONG i = 0; i < pSysHandleInfo->NumberOfHandles; i++)
{
    PSYSTEM_HANDLE pHandle = &(pSysHandleInfo->Handles[i]);

    if(pHandle->ProcessId == pid)
    {
     int a=10;
    }

    if (pHandle->ProcessId == pid &&
        pHandle->ObjectTypeNumber == HANDLE_TYPE_FILE)
    {
        dwFiles++;  // Increase the number of file handles

        // Duplicate the handle in the current process
        HANDLE hCopy;
        if (!DuplicateHandle(hProcess, (HANDLE)pHandle->Handle,
            GetCurrentProcess(), &hCopy, MAXIMUM_ALLOWED, FALSE, 0))
            continue;

        // Retrieve file name information about the file object.
        IO_STATUS_BLOCK ioStatus;
        PFILE_NAME_INFORMATION pNameInfo = (PFILE_NAME_INFORMATION)
            malloc(MAX_PATH * 2 * 2);
        DWORD dwInfoSize = MAX_PATH * 2 * 2;

        if (NtQueryInformationFile(hCopy, &ioStatus, pNameInfo,
            dwInfoSize, FileNameInformation) == STATUS_SUCCESS)
        {
            // Get the file name and print it
            WCHAR wszFileName[MAX_PATH + 1];
            StringCchCopyNW(wszFileName, MAX_PATH + 1,
                pNameInfo->FileName, /*must be WCHAR*/
                pNameInfo->FileNameLength /*in bytes*/ / 2);

            wprintf(L"0x%x:\t%s\n", pHandle->Handle, wszFileName);
        }
        free(pNameInfo);

        CloseHandle(hCopy);
    }
}

CloseHandle(hProcess);

HeapFree(GetProcessHeap(), 0, pSysHandleInfo);

// Return the number of file handles in the process
return dwFiles;
}

int _tmain(int argc, _TCHAR* argv[])
{
ULONG pid = GetCurrentProcessId();
DWORD dwFiles = EnumerateFileHandles(4592);

_tprintf(TEXT("\r\n"));

// Get file name from file handle using a file mapping object
HANDLE hFile;
hFile = CreateFile(TEXT("test.txt"), GENERIC_WRITE | GENERIC_READ,
    0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
    _tprintf(TEXT("CreateFile failed with %d\n"), GetLastError());
    return 0;
}

BYTE bWriteBuffer[] = "0123456789";
DWORD dwBytesWritten;

// Write 11 bytes from the buffer to the file
if (!WriteFile(hFile,                // File handle
    bWriteBuffer,                    // Buffer to be write from
    sizeof(bWriteBuffer),            // Number of bytes to write
    &dwBytesWritten,                 // Number of bytes that were written
    NULL))                           // No overlapped structure
{
    // WriteFile returns FALSE because of some error

    _tprintf(TEXT("Could not write to file w/err 0x%08lx\n"), GetLastError());
    CloseHandle(hFile);
    return 0;
}

//GetFileNameFromHandle(hFile);
CloseHandle(hFile);

return 0;
}

Any help how handle is programmatically searching for process usage of device by physical device object information.

A: Your code uses only file handles of given process:
if (pHandle->ProcessId == pid && pHandle->ObjectTypeNumber == HANDLE_TYPE_FILE)

When you get a handle via SystemHandleInformation, you should check it's type and based on it's type, do something. As you see in your example if handle is file handle, it gets it filename via NtQueryInformationFile. So you should do a similar task on every handle type you want.
Using NtQueryObject function in ntdll, you can get type of a handle. In this example, every handle of a process used to print some information based on it's type.