text:
Q: Dynamically added  elements not visible on UI I am trying to add  elements dynamically from $.ajax's done() function:
$.ajax({
        url: getAllTemplates,
        method: "POST",
        data: form_data,
        contentType: false,
        cache: false,
        processData: false
    })
        .done(function (data) {
            let templates = JSON.parse(data);
            console.log(templates);
            let template_dropdown = $('#template');

            $.each(templates, function (key, value) {
                template_dropdown.append($('<option></option>').attr("value", value['name']).text(value['name']));
            });

        })
        .fail(function (jqXHR, textStatus, errorThrown) {
            // do something
        });

I can see following markup in console as well as on view source of browser:

But, it is not getting displayed in actual dropdown in browser:

Any clue as to what's going wrong here?

A: If you are adding dynamically options to the dropdown then you must need to call below function just before adding option
$('.selectpicker').selectpicker('refresh');
exactly after adding options will update the selectpicker option and make it visible.


text:
Q: Node.js encrypt a string into alphanumerical I am currently using NPM module crypto-js to encrypt strings. The codes are the following:
CryptoJS.AES.encrypt("hello", "secrete_key").toString()

This yields to an encrypted string of: U2FsdGVkX1/G276++MaPasgSVxcPUgP72A1wMaB8aAM=
Notice that in the encrypted string, there are special symbols such as / + and =. These generated special symbols cause a problem in my app. Is there a way that I can encrypt a string into only alphanumericals? I like the way crypto-js is doing, since it is simple. I only need to feed in the string, and a password hash. If crypto-js cannot, what other modules can achieve this in a simple and straight-forward way?

A: CryptoJS also includes utilities for encoding/decoding so you can convert your encrypted string to a URL-safe format. See the CryptoJS docs for more info.
For example:
var CryptoJS = require("crypto-js");

let encrypted = CryptoJS.AES.encrypt("hello", "secrete_key").toString()
var encoded = CryptoJS.enc.Base64.parse(encrypted).toString(CryptoJS.enc.Hex);

console.log(encrypted)
console.log(encoded)

var decoded = CryptoJS.enc.Hex.parse(encoded).toString(CryptoJS.enc.Base64);
var decrypted = CryptoJS.AES.decrypt(decoded, "secrete_key").toString(CryptoJS.enc.Utf8);

console.log(decoded)
console.log(decrypted)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create a background service in android remotely I want to create a service whose function will not be known forehand. When the app is started, the function (which is decided at run time) to be performed is sent from the server to the mobile.
For example, when the app runs server may ask to list all installed apps in the mobile and app replies. When developing the app we dont know that server is going to ask for installed apps. App should be able to respond to any command from the server.
Android app acts like a client to all commands from the server.

A: Apply the push notification, while on receive the notification, start your service with the tasks sent by the server.


text:
Q: Why is compiler requesting reference to Entity Framework in User Interface project? I am trying to learn how to create a Winform C# app, that uses EF with repository pattern.
From my understanding, UI layer should be independent from Entity Framework (it uses data through repository and it shouldn't care if there is an Entity framework or any other data provider), but compiler is showing and error if WinForms project is not having reference to Entity framework (when I add reference to EF, everything works fine)
Error message
No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'. Make sure the provider is registered in the 'entityFramework' section of the application config file
Why compiler needs my Winform project to have reference to Entity framework?
Code from Winforms project
    private void MainForm_Load(object sender, EventArgs e)
    {
        //Customer is a POCO class
        using (var customers = new EfRepository<Customer>())
        {
            foreach (var c in customers.All())
            {
                CList.Items.Add(c.CustomerName);
            }
        }
    }

    private void SaveCustomerButton_Click(object sender, EventArgs e)
    {
        var newCustomer=new Customer();
        newCustomer.CustomerName = CName.Text;
        newCustomer.CustomerDescription = CDescription.Text;
        //newCustomer.
        using (var customers = new EfRepository<Customer>())
        {
            customers.Add(newCustomer);
            customers.Commit();
        }
    }

Code from Repository project
public class EfRepository<T> : IRepository<T>, IDisposable where T : class//, IEntity<int>
{
    private FirstContext _ctx = new FirstContext();
    private DbSet<T> _set;

    public EfRepository()
    {
        //_ctx = _context;
        _set = _ctx.Set<T>();
    }
    public void Add(T newEntity)
    {
        _set.Add(newEntity);
    }
    public IQueryable<T> All()
    {
        return _set;
    }

Context
public class FirstContext : BaseContext<FirstContext>
{
    public DbSet<Customer> Customers{ get; set; }
}

[EDIT]
I added app.config (to my UI project) with information about my database, but it works only if I add Entity Framework to my UI project, if I remove EF from my UI project repository that connects to database is not returning any data (no error as well...)
Here is content of my app.config:
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <connectionStrings>
    <add name="RepositoryDb" connectionString="Data Source=.;Initial Catalog=RepositoryDb;Integrated Security=True;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

A: You are right that your GUI projects should not need the EF assemblies directly. It will off course still load them through your Repository project.
But an application uses, by default, only 1 config file.
So you do need the db settings in app.config, like the error is telling you.
When you added the EF libs, there were probably a few changes in the config file. Maybe it'll keep working when you remove the libs again.

A: After putting the config file in the main app, this was what solved my problem
 public PSContext() : base()
        {

            var type = typeof(System.Data.Entity.SqlServer.SqlProviderServices);
        }

No more errors...


text:
Q: ExpressionEngine: Adding BrilliantRetail members into Campaign Monitor using Campaigner I have an ExpressionEngine store. I use BrilliantRetail for the store. A person can register through a form or be automatically registered when the buy a product. I'm using Campaigner to automatically put members into a specific mailing list on Campaign Monitor. I can't get these to all play nice together:
I've confirmed that a member is automatically going into Campaign Monitor when I register through the EE backend.
I've confirmed the member flow works in BrilliantRetail.
Does anyone have any suggestions/ideas?

A: Do you have SQL access via phpMyAdmin or similar? Because the first thing to look at is extension priority, in the exp_extensions table. Check if BR and Campaigner are using any of the same hooks; if so, make sure that BR has a LOWER number in the 'priority' column.


text:
Q: Why are interfaces not able to be marked as sealed? public sealed interface IMyInterface
{
}

Gives "The modified 'sealed' is not valid for this item"
I can understand in some ways that an interface must be descendable otherwise the class cannot implement it.
But why can I not specify that an interface should not have a sub interface defined or is there a way, just not with sealed?
Edit
I should have made some effort to explain why I would want this. I often see interface inheritence chains where the dev should be using composition instead. Sealed is ideal for this in classes and I wondered if there was a way to enforce the same for interfaces. As unnessasary inheritence makes it harder to refactor and maintain in my opinion.
Edit 2
On reflection of the comments and posts, interface inheritence trees can't be anywhere near as complex as object inheritence trees. As when you are deriving from another interface IX all you are saying is "must also implement IX". And preventing that has no benefit.

A: sealed in the context of an interface would mean no class can implement this interface. That would be useless, hence its not allowed.

A: The purpose of sealing a class, or a virtual method of a class, is to lower your costs. Designing for inheritance is expensive, and if you do not do it correctly, it is dangerous. There are security, correctness and robustness consequences to improperly designing for inheritance, so if you do not intend to design for inheritance, it is wise to seal your class and thereby avoid the costs associated with designing for inheritance.
Classes need to be designed for inheritance because they have implementation details. Interfaces have no implementation details. There is no cost associated with interfaces being inheritable. And therefore there is no incentive to add the feature of allowing interfaces to be sealed.

A: It would just be confusing. Using the standard syntax, it would imply that you cannot implement the interface. Also, interfaces don't contain any functionality or fields, so there is no practical use in sealing it. An interface is more or less a contract.
Sealing an interface from "interface inheritance" would not do anything, since people could just implement your interface and the other one that would have inherited your interface.

A: The sealed keyword is simply not designed (and makes no sense) for interfaces. See the msdn documentation http://msdn.microsoft.com/en-us/library/88c54tsw(v=vs.71).aspx

A: Sealed is a keyword for a class. The goal of interfaces is for classes to implement any contracts they define. You can seal the class that implements an interface, but sealing an interface would be of little use.

A: Interfaces is your Application Contract...When you don't need to your contract why you define it?

A: One of the primary purposes of sealing a class is to require any storage locations of that class to hold instances of that precise type, rather than a derived type.  Even though most code won't mind when derived-type objects are substituted for base-type objects, there are many situations where such substitution can be problematic.  For example, some classes include a function to perform a relative comparison with another object of the same type, with the expectation that the comparison results will yield a sortable sequence.  If types Bar and Boz both derive from Foo, and use any Bar-specific or Boz-specific fields in the comparison, it may be impossible to sensibly sort sequences holding a mixture of Bar and Boz instances.
Such a purpose would not exist with interfaces, since by their nature interfaces are designed to be implemented by multiple classes.  An interface which couldn't be implemented by any classes would be useless, and an interface which could only be implemented by one class would be pointless (if IFoo can't be anything other than a Foo, one might as well simply use Foo everyplace one would be inclined to use IFoo).
There would be some usefulness to restricting implementations of an interface to the module where it's defined, and/or allowing interfaces to have internal members.  I don't know any particular reason why that isn't allowed, nor even whether allowing or disallowing such things would have been "easier" or "harder" than forbidding them.

A: To me, interface implies an abstract keyword; so if an interface would be sealed, it would be sealed abstract what seems to be a contradiction.


text:
Q: Want to do work on my Application Uninstall:android i am aware of android BROADCAST_PACKAGE_REMOVED for notify when any application is uninstalling from device.
Now it is possible that when i uninstall one application and that application do some work before and uninstall.
e.g: my application work with android contact if application uninstall at that time i want to change in contact data.
can i get any event for uninstalling app?
Thanks.

A: No.
(at least until the current version of Android)
In case it's any help, widgets do get notified when their last instance is removed. However, the app than contains the widget remains installed.


text:
Q: Geo Data API - getAutocompletePredictions behaving wierdly I am building an android app which is using Places.GeoDataApi.getAutoCompletePredictions method. I have followed this tutorial - https://github.com/googlesamples/android-play-places/tree/master/PlaceComplete/Application/src/main/java/com/example/google/playservices/placecomplete
In an attempt to make this work, I have literally copied the code from this link. But somehow, my code does not execute after the line where this 'autocompletePredictions' method is called, i.e., does not work after line 169 in PlacesAutocompleteAdapter.java file in the example link above.
My code does not give any exception, nor any error, or any thing in log. It just does not execute after this line.
Can someone suggest what is going wrong? Did I not include any play-services in my gradle (I have included location-play-service:7.5.0)? or am I missing something in my manifest?
Please help. I have been scratching my head now for 2 days!

A: I figured the answer out. While setting up GeoDataApi, I was not using Locations.API. Also, the configurations in my AndroidManifest.xml was wrong.


text:
Q: Firebase: Oncancelled method fired after calling firebaseAuth signout In Android activity onCreate() method, a firebase reference is invoked on  addvalieEventListener() as shown below.
The callbacks are working as expected however,when FirebaseAuth.getInstance().signOut(); is called via options menu, onCancelled() is fired, why?
dbref.child("users").addValueEventListener(new ValueEventListener() {
 @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.e(TAG,"a ERROR:"+databaseError.toString());

        }
    });

optionsmenu snippets
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.sign_out_menu: // preferences settings
        {
            Toast.makeText(this, "signout", Toast.LENGTH_SHORT).show();
            FirebaseAuth.getInstance().signOut();

            SharedPreferences.Editor editor = getSharedPreferences("test",MODE_PRIVATE).edit();
            editor.putBoolean("Active",false);
            editor.commit();

            Intent intent = new Intent(ProfileviewActivity.this, SignInActivity.class);
            startActivity(intent);
            finish();
        }
        break;

    }
    return false;
}


text:
Q: FileNotFoundException when trying to read a file I've written I am trying to write an object (pilotRecord) to a file and read it back again. I understood that I didn't need to specify a path as it is internal to my app, so I want all files deleted if the app is uninstalled.
Here's my code:
    fileoutputstream = openFileOutput("test1", Context.MODE_WORLD_WRITEABLE);
    Log.d(this.getClass().getName(), "loadPilotRecord: "+fileoutputstream.toString());
    objectoutputstream = new ObjectOutputStream(fileoutputstream);
    Log.d(this.getClass().getName(), "loadPilotRecord: "+objectoutputstream.toString());
    objectoutputstream.writeObject(pilotRecord);
    objectoutputstream.close();
    fileoutputstream.close();

    fileinputstream = new FileInputStream("test1");
    Log.d(this.getClass().getName(), "loadPilotRecord: "+fileinputstream.toString());
    objectinputstream = new ObjectInputStream(fileinputstream);
    Log.d(this.getClass().getName(), "loadPilotRecord: "+objectinputstream.toString());
    pilotRecord = (PilotRecord)objectinputstream.readObject();
    objectinputstream.close();
    fileinputstream.close();

My problem is that I get a FileNotFoundException on the following line in the above code:
fileinputstream = new FileInputStream("test1");
I'm not really sure how to find out what path it is using, or maybe there is a more obvious problem I'm just not seeing.
Sorry if this is a bit basic, but I'm still trying to find my feet.
The Log.d statements just output the class name and an Id.
TIA,

*

*Frink

A: Have you tried openfileinput("test1) instead of new FileInputStream("test1")?

A: To find out which path is actually used try:
File f = new File("test1");
Log.d(this.getClass().getName(), f.getAbsolutePath());

Look at this location if the file is really created - if not, you won't be able to read.
EDIT: removed the guess with flush which was quite some nonsense


text:
Q: How can I ensure that 'fs.appendFileSync' never succeeds partially? Up until now, my assumption has been that if fs.appendFileSync throws an exception, then it is guaranteed that the contents of the target file haven't changed one bit.
The official documentation of this function doesn't refer to this issue (and to failure cases in general).
The source code of this function shows that it calls fs.writeFileSync, which in turn does this:
  try {
    while (length > 0) {
      const written = fs.writeSync(fd, data, offset, length, position);
      offset += written;
      length -= written;
      if (position !== null) {
        position += written;
      }
    }
  } finally {
    if (!isUserFd) fs.closeSync(fd);
  }

Can I infer from the above that fs.appendFileSync may throw an exception after partially changing the target file?
If yes, then are there any known tools or paradigms for tackling this rather-difficult-to-handle situation?

A: Yes, fs.appendFileSync doesn't support any form of transactions afaik. While i do not know any partical nodeJS-module for this use case, you could do it manually by

*

*duplicating the file

*appending to the duplicate tmp-file

*renaming/replacing the original file with the tmp file


text:
Q: How to access a layer inside UIView custom class generate with Paintcode? I'm using Paintcode V3 and last Xcode for my project.
In Paintcode I draw a red path, kind of "clock hand" with a radius variable to be able to rotate it.

In my Xcode project, this custom UIView is added to a main view.
When the red path is rotating, I need to know when it intersects with another element of the view.
I tried:
if self.redPathView.frame.intersects(self.anotherView.frame) {
    //do something...
}

but it can't work because redPathView is the entire Paintcode canvas (the square frame) and not only the red path.
I'm searching a way to access to the red path of my view.

A: Interesting problem.
I don't think there is a way to do exactly what you are looking for...
Like you mentioned, when we use PaintCode, our custom drawings become an entire UIView.
We can't access its specific elements (like your redPathView).
(I'm favoriting this question in case anyone knows if we actually can. I may be wrong.)
Anyway, there is a workaround. You could use PaintCode itself to tell you when "collisions" happen. Of course, then you would need to draw everything there... And implement some sort of internal control that would make sense to you.
For example, in the picture below I created this "clock hand", with functions to detect when the red thing touches other UI elements (key point there is the touchedElementID expression -- observe how it updates itself with the "ID" of the rectangles):

There are some issues you may find with this approach, for example the need to know the exact position of other elements on the screen and possibly complex ternary constructions like:
(rotationSanitized <= -352 || rotationSanitized >= -8) ?
1 :
(rotationSanitized <= -82 && rotationSanitized >= -98) ?
2 :
(rotationSanitized <= -172 && rotationSanitized >= -188) ?
3 :
(rotationSanitized <= -262 && rotationSanitized >= -278) ?
4 : 0

Also, how to "export" and consume this information along with the StyleKit in Xcode?
The trick I did was to add an empty (no Fill, no Stroke) UI element in PaintCode and associate the touchedElementID expression result to the alpha value of the element.
This way I could access the expression in my custom view, for example via StyleKit.touchedElementID. But that introduces a new problem since now I have to change the generated StyleKit every time it is exported (two lines of code, but still). That is kind of a fragile solution.
However, if you are ok with that, then it's just a matter of consuming this new information...
For that I created a protocol, so my ViewController can act as the delegate of my custom view, and perform whatever it needs to do when the most internal UI elements in PaintCode are "touched".
Here is the final result:

Finally, check this project in GitHub with all the code and samples.


text:
Q: No idea why players are able to take from bukkit GUI So I am attempting to make a bukkit plugin where I use a GUI inventory to add buttons and run commands. I blocks in this inventory however users are able to take them out and put blocks in. I would like some help!
//Init gui
     public static Inventory gui = Bukkit.createInventory(null, 54, "Punish");

From what I understand I need a inventory click event, this is what I have...
 @EventHandler
       public void onInventoryClick(InventoryClickEvent event) {
       Player player = (Player) event.getWhoClicked(); // The player that clicked the item
       ItemStack clicked = event.getCurrentItem(); // The item that was clicked
       Inventory inventory = event.getInventory(); // The inventory that was clicked in
       if (event.getInventory().getTitle().equals("Punish")) {
           event.setCancelled(true);
       }
       }

Thanks!

A: To prevent players and blocks (e.g. hoppers) to move items in/to/from an inventory, cancel the the InventoryMoveItemEvent for items you don't wish to move.


text:
Q: Android build variant not working with different flavors I have approx 20 different flavors in my application. Previously it was working fine since last 1 year, But after updating to new gradle version 4.4 it starts raising an issue which is No matching client found for package name.
Note: Only default flavor is working file now.
Please advise me to fix this issue,
I have fixed that issue now error is
Error:cannot access Hide
Error:Execution failed for task ':app:compileKissgc_customerDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

    android {
        compileSdkVersion 26
        buildToolsVersion '26.0.2'
        defaultConfig {
            applicationId 'com.mobile.test'
            minSdkVersion 15
            targetSdkVersion 26

            multiDexEnabled true
            versionCode 46
            versionName "1"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                // minifyEnabled true
                false

    //            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
    //                    'proguard-rules.pro'
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
        lintOptions {
            checkReleaseBuilds false
        }
        productFlavors {
            test{
                minSdkVersion 19
                applicationId 'com.mobile.test'
                targetSdkVersion 27
                versionCode 46
                versionName '1.0'
                flavorDimensions "default"
    //            deploy = "release|staging"
            }
            test1{
                minSdkVersion 19
                applicationId 'com.mobile.test1'
                targetSdkVersion 27
                versionCode 7777810
                versionName '1.0'
            }
}

  compile ("android.arch.persistence.room:runtime:1.0.0") {
        exclude group: 'com.android.support'
    }
    compile 'com.google.firebase:firebase-crash:12.0.1'
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile('com.stripe:stripe-android:1.0.4@aar') {
        transitive = true;
    }

    compile 'com.android.support:appcompat-v7:26.1.0'
    compile('com.crashlytics.sdk.android:crashlytics:2.9.1@aar') {
        transitive = true
    }
   // compile 'com.google.firebase:firebase-core:12.0.1'
//    compile 'com.google.android.gms:play-services:16.0.0'
    compile 'com.github.drawers:SpinnerDatePicker:1.0.6'
    compile 'info.hoang8f:android-segmented:1.0.6'
    implementation 'com.google.android.gms:play-services-wallet:16.0.0'

Thanks
Amit Sharma

A: In new gradle version, it is mandatory to define flavorDimensions before defining the productflavors. If you don't have any dimensions to mentioned. Then by default, you have to define flavorDimensions "default"
 flavorDimensions "default"
    productFlavors {
        test {
            applicationId "com.example.test"
        }

        tester {
            applicationId "com.example.tester"
        }
}

A: Dimensions should be defined in above scope, not in each flavor
Each flavor should refer an existing dimension
flavorDimensions "default"
productFlavors {
            test{
                dimension "default"
                minSdkVersion 19
                applicationId 'com.mobile.test'
                targetSdkVersion 27
                versionCode 46
                versionName '1.0'
    //            deploy = "release|staging"
            }
            test1{
                dimension "default"
                minSdkVersion 19
                applicationId 'com.mobile.test1'
                targetSdkVersion 27
                versionCode 7777810
                versionName '1.0'
            }
}


text:
Q: Access OpenId-Connect IDP via Keycloak with additional Basic Auth We are currently evaluating the possibilities of keycloak since we need to replace a custom SSO solution. This requires us to connect to external IDPs which we already connected to.
Currently I am investigating an OpenID-Connect Provider which is authenticating the clients via POST using client_id and client_secret as parameters. Additionally, its API is secured with a basic authentication via the Authorization header. Whilst the first part is no problem, I have not found a solution to overcome the additional basic authentication with the available default configurations (using a user-defined OpenID Connect V1.0 provider). Vice versa, I can overcome the basic authentication, but then will miss the client_id and client_secret parameters which results in an error of the IDP not returning an access token.
Is there a way to resolve this issue? If not via default options, is there an option to add custom IDPs which can be configured in the backend? I saw the SPIs in the developer documentation (https://www.keycloak.org/docs/latest/server_development/#_providers) but I am not sure if one of those suits our needs.


text:
Q: hibernate avoid the id It's the first time I'm using hibernate, so forgive me if I'm going to ask for easy advice. I'm currently mapping a class using the xml (no annotations), I don't have the id on my table, but someone told me that I'm compeled to use an ID using hibernate, so, I created the SMS_MONITORING_ID field into the table and I'm mapping it as following:
 <class name="smsbox.dal.model.SmsMonitoring" table="MST_SMS_MONITORING">
    <comment></comment>

    <id name="smsMonitoringId" type="long">
        <column name="SMS_MONITORING_ID" />
        <generator class="native" >
            <param name="sequence">ID_SMS_MONITORING</param>
        </generator>

    </id>

I already made a sequence on my oracle database (ID_SMS_MONITORING), and I don't want that hibernate handle the id at all, I even would like to avoid any reference to the id in my java code (when I save the object).
How could I accomplish my will to let hibernate ignoring the whole process in assigning the id ?
P.S I'm mapping the id (long) into an Oracle "Number" type, what is the rule to avoid possible problem (long dosen't fit into number or vice-versa) can anybody provide me some link that explaing well the mapping types Hibernate and Oracle DB (I didn't find anything interesting on my own).
Thanks

A: Unfortunately, every mapped entity should have ID mapped as every relational database demands it.
The ID is assigned to the object only when you persist your object, so you need to use your sequence in Hibernate. More than this, you need to create equals and hashcode functions with more parameters than ID, because if you have two objects and their IDs are null and your equals and hashcode functions are using ID only, both objects are equal in Hibernate and might be the root cause for a lot of problems in your code.

A: If you refer to the Hibernate documentation:
http://docs.jboss.org/hibernate/core/3.3/reference/en/html/mapping.html#mapping-declaration-id
you'll see that the  tag is optional. Leaving it undefined is equivalente to set it as "assigned" (in other words, your application will handle the id assignment).

A: You may try to declare the id generator as following
 <generator class="sequence">
        <param name="sequence">YourSquenceName</param>
      </generator>

when you save your object with hibernate, you dont have to get/set Id, and just leave the id field as null, Hibernate will get an valid id from your sequence.


text:
Q: How do I unregister an Archetypes schema extender? I'm trying to uninstall collective.carousel's archetypes schemaextender (I'm only interessed in the portlet from that package, not adding Carousel source to every PloneFormGen field etc).
I've tried to unregister the adapter using a import-step, but have so far failed.
def unregister_carousel_extender(site):
    from collective.carousel.schemaextender import ContentTypeExtender
    from archetypes.schemaextender.interfaces import ISchemaExtender
    from Products.ATContentType.interfaces import IATContentType

    sm = site.getSiteManager()
    sm.unregisterAdapter(factory=ContentTypeExtender, provided=(ISchemaExtender,), required=(IATContentType), name=u'')

I've also spent time in pdb without any success. I'm able to get hold of the registered adapters and can see that collective.carousel.schemaextender.ContentTypeExtender is registered as an unnamed adapter.

A: You can't unregister on an import step. Import steps only run when you import the profile. In contrast zcml declarations will be parsed and executed when you start your instance. So make sure you unregister after the adapter has been registered, every time.

A: The 'required' parameter needs to be a sequence of interfaces rather than a single interface. So, required=[IATContentType] or required=(IATContentType,) (note the comma!) rather than required=(IATContentType).
You can check the return value from unregisterAdapter to find out if it was successful...if it's False, it didn't find the adapter you specified (which usually means one of the parameters is incorrect).

A: What you want is to undo some zcml of collective.carousel when Zope starts up.  You can do that with the z3c.unconfigure package.
(Note that I am not sure if the portlet of collective.carousel still works correctly when you have unconfigured this part of the zcml.)


text:
Q: TikZ distinct random integers I am trying to generate BINGO cards where but all the number in the card must be distinct. Here is what I got so far:
\documentclass[a4paper]{article}
\usepackage{xstring}
\usepackage{tikz}
\usetikzlibrary{calc}

\def\NumOfColumns{5}%
\def\Sequence{1/A/1/15, 2/B/16/30, 3/C/31/45, 4/D/46/60, 5/E/61/71}%

\newcommand{\Size}{1.5cm}
\tikzset{Square/.style={
    inner sep=0pt,
    text width=\Size,
    minimum size=\Size,
    draw=black,
    fill=white,
    align=center,
    }
}

\begin{document}

\begin{tikzpicture}[draw=black, ultra thick, x=\Size,y=\Size]
    \node [Square] at ($(0.5,-0.5)-(0,0)$) {\Huge B};
    \node [Square] at ($(0.5,-0.5)-(-1.0,0)$) {\Huge I};
    \node [Square] at ($(0.5,-0.5)-(-2.0,0)$) {\Huge N};
    \node [Square] at ($(0.5,-0.5)-(-3.0,0)$) {\Huge G};
    \node [Square] at ($(0.5,-0.5)-(-4.0,0)$) {\Huge O};
    \foreach \row/\rowLetter/\MinNumber/\MaxNumber in \Sequence{%
        \foreach \col/\colLetter/\MinNumber/\MaxNumber in \Sequence {%
            \pgfmathtruncatemacro{\value}{\col+\NumOfColumns*(\row-1)}
            \def\NodeText{\pgfmathparse{random(\MinNumber,\MaxNumber)}\pgfmathresult}
            \pgfmathsetmacro{\ColRowProduce}{\col*\row}
            \IfEq{\ColRowProduce}{9}{% If is center square
                \node [Square] at ($(\col,-\row)-(0.5,0.5)$) {\Huge X};
            }{
                \node [Square] at ($(\col,-\row)-(0.5,0.5)$) {\Huge \NodeText};
            }
        }
    }
\end{tikzpicture}
\end{document}

In this code a column can have repeated numbers. How can I avoid it?

A: I used to define a \pgfmathrandomitemnorepeat which is compatible with pgfmath's \pgfmathdeclarerandomlist and \pgfmathrandomitem.
The syntax is exactly the same: first use

\pgfmathdeclarerandomlist{⟨list name⟩}{{⟨item-1⟩}{⟨item 2⟩}...}

and then

\pgfmathrandomitemnorepeat{⟨macro⟩}{⟨list name⟩}

\documentclass[a4paper]{article}
\usepackage{xstring}
\usepackage{tikz}
\usetikzlibrary{calc}

\makeatletter
    \def\glet{\global\let}
    \def\pgfmathrandomitemnorepeat#1#2{%
        \pgfmath@ifundefined{pgfmath@randomlist@#2}{\pgfmath@error{Unknown random list `#2'}}{%
        \xdef\pgfmath@randomlistlength{\csname pgfmath@randomlist@#2\endcsname}%
        \pgfmathrandominteger{\pgfmath@randomtemp}{1}{\pgfmath@randomlistlength}%
        \expandafter\glet\expandafter#1\csname pgfmath@randomlist@#2@\pgfmath@randomtemp\endcsname%
        \expandafter\glet\expandafter\pgfmathrandomlist@lastitem\csname pgfmath@randomlist@#2@\pgfmath@randomlistlength\endcsname%
        \expandafter\glet\csname pgfmath@randomlist@#2@\pgfmath@randomtemp\endcsname\pgfmathrandomlist@lastitem%
        \expandafter\pgfmathtruncatemacro\csname pgfmath@randomlist@#2\endcsname{\pgfmath@randomlistlength-1}%
        \expandafter\xdef\csname pgfmath@randomlist@#2\endcsname{\csname pgfmath@randomlist@#2\endcsname}%
    }}
    \pgfmathdeclarerandomlist{1-100}{
        {00}{01}{02}{03}{04}{05}{06}{07}{08}{09}
        {10}{11}{12}{13}{14}{15}{16}{17}{18}{19}
        {20}{21}{22}{23}{24}{25}{26}{27}{28}{29}
        {30}{31}{32}{33}{34}{35}{36}{37}{38}{39}
        {40}{41}{42}{43}{44}{45}{46}{47}{48}{49}
        {50}{51}{52}{53}{54}{55}{56}{57}{58}{59}
        {60}{61}{62}{63}{64}{65}{66}{67}{68}{69}
        {70}{71}{72}{73}{74}{75}{76}{77}{78}{79}
        {80}{81}{82}{83}{84}{85}{86}{87}{88}{89}
        {90}{91}{92}{93}{94}{95}{96}{97}{98}{99}
    }

\def\NumOfColumns{5}%
\def\Sequence{1/A/1/15, 2/B/16/30, 3/C/31/45, 4/D/46/60, 5/E/61/71}%
\newcommand{\Size}{1.5cm}
\tikzset{Square/.style={
    inner sep=0pt,
    text width=\Size,
    minimum size=\Size,
    draw=black,
    fill=white,
    align=center,
    }
}
\begin{document}

\begin{tikzpicture}[draw=black, ultra thick, x=\Size,y=\Size]
    \node [Square] at ($(0.5,-0.5)-(0,0)$) {\Huge B};
    \node [Square] at ($(0.5,-0.5)-(-1.0,0)$) {\Huge I};
    \node [Square] at ($(0.5,-0.5)-(-2.0,0)$) {\Huge N};
    \node [Square] at ($(0.5,-0.5)-(-3.0,0)$) {\Huge G};
    \node [Square] at ($(0.5,-0.5)-(-4.0,0)$) {\Huge O};
    \foreach \row/\rowLetter/\MinNumber/\MaxNumber in \Sequence{%
        \foreach \col/\colLetter/\MinNumber/\MaxNumber in \Sequence {%
            \pgfmathtruncatemacro{\value}{\col+\NumOfColumns*(\row-1)}
            \pgfmathrandomitemnorepeat\NodeText{1-100}
            \pgfmathsetmacro{\ColRowProduce}{\col*\row}
            \IfEq{\ColRowProduce}{9}{% If is center square
                \node [Square] at ($(\col,-\row)-(0.5,0.5)$) {\Huge X};
            }{
                \node [Square] at ($(\col,-\row)-(0.5,0.5)$) {\Huge \NodeText};
            }
        }
    }
\end{tikzpicture}
\end{document}

A: You can also store the already used values i a list, compare the new value with it and get another one, if it was in the list.
\documentclass[a4paper]{article}
\usepackage{xstring}
\usepackage{tikz}
\usetikzlibrary{calc}

\def\NumOfColumns{5}%
\def\Sequence{1/A/1/15, 2/B/16/30, 3/C/31/45, 4/D/46/60, 5/E/61/71}%

\newcommand{\Size}{1.5cm}
\tikzset{Square/.style={
    inner sep=0pt,
    text width=\Size,
    minimum size=\Size,
    draw=black,
    fill=white,
    align=center,
    }
}

\newif\ifNumberNotUnique

\begin{document}

\begin{tikzpicture}[draw=black, ultra thick, x=\Size,y=\Size]
    \node [Square] at ($(0.5,-0.5)-(0,0)$) {\Huge B};
    \node [Square] at ($(0.5,-0.5)-(-1.0,0)$) {\Huge I};
    \node [Square] at ($(0.5,-0.5)-(-2.0,0)$) {\Huge N};
    \node [Square] at ($(0.5,-0.5)-(-3.0,0)$) {\Huge G};
    \node [Square] at ($(0.5,-0.5)-(-4.0,0)$) {\Huge O};
    % initialize list of used numbers, needs to be global
    \xdef\NumbersUsed{0}
    \foreach \row/\rowLetter/\MinNumber/\MaxNumber in \Sequence{%
        \foreach \col/\colLetter/\MinNumber/\MaxNumber in \Sequence {%
            \pgfmathtruncatemacro{\value}{\col+\NumOfColumns*(\row-1)}
            % primitive \loop, because a repeat-until is needed
            \loop
                \pgfmathtruncatemacro{\NodeText}{random(\MinNumber,\MaxNumber)}
                % also the \ifNumberNotUnique need to be global
                \global\NumberNotUniquefalse
                % test all used numbers against new number
                \foreach \NewNumber in \NumbersUsed{%
                    \IfEq{\NewNumber}{\NodeText}{%
                        \global\NumberNotUniquetrue
                    }{}%
                }
            \ifNumberNotUnique
            \repeat
            % add new number to list
            \xdef\NumbersUsed{\NumbersUsed,\NodeText}
            \pgfmathsetmacro{\ColRowProduce}{\col*\row}
            \IfEq{\ColRowProduce}{9}{% If is center square
                \node [Square] at ($(\col,-\row)-(0.5,0.5)$) {\Huge X};
            }{
                \node [Square] at ($(\col,-\row)-(0.5,0.5)$) {\Huge \NodeText};
            }
        }
    }
\end{tikzpicture}

% for debugging
\NumbersUsed\quad\ifNumberNotUnique Shit\else Ok\fi
\end{document}

(This solution has also the advantage that the numbers in the columns stay within the range given in \Sequence, if this is of any concern.)


text:
Q: How can I pass my login details to a web page?

Required Information

        E-mail
        <input class="" id="email" type="email" name="email" value="" placeholder="example: username@domain.com" required aria-required="true" aria-described-by="email-tip" />
        This is the e-mail address you used to register with edX

        Password
        <input id="password" type="password" name="password" value="" required aria-required="true" />

I am trying to write some code that will parse a webpage and check for updated content periodically, my problem is that I need to be logged in but I am unsure how to pass in my login details, the above is some of the source of the login page, how is it possible to achieve this?
I have tried something like the code below but to no avail.
browser = mechanize.Browser()
browser.open("https:xxxx")
browser.select_form(nr = 0)
browser.form['username'] = "email"
browser.form['password'] = "xxxxx"
browser.submit()

A: At least, the field is called email, not username:
browser.form['email'] = "email"
browser.form['password'] = "xxxxx"
browser.submit()

A: store the last updated date time in a variable and have a javascript timer function to invoke a function to check the last updated date time and if the content was updated more than the predefined time, make a call to backend and update the info on the page.
FYI.. there is no browser object. there is document object which has properties and methods to manipulate the page


text:
Q: How to add Event in React Functional Component I have a question about React functional components, specifically about functions in functional components. For instance:
import React, { useEffect } from 'react';

const Component = (props) => {
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
  });
  useEffect(() => {
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  function handleScroll() {
    let scrollTop = window.scrollY;
  }

  return ()
}

A: This is just a quick demo on how to use useEffect to subscribe to event, useRef to create element ref for event listener, and useState to store the event results.
Please note that this is for the sake of demonstration purpose only. Calling setState in every tick of scroll event callback is NOT ideal.
import React, { useState, useEffect, useRef } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

const App = () => {
  // set default value
  const [scrollTop, setScrollTop] = useState(document.body.scrollTop);

  // create element ref
  const innerRef = useRef(null);

  useEffect(() => {
    const div = innerRef.current;
    // subscribe event
    div.addEventListener("scroll", handleOnScroll);
    return () => {
      // unsubscribe event
      div.removeEventListener("scroll", handleOnScroll);
    };
  }, []);

  const handleOnScroll = (e) => {
    // NOTE: This is for the sake of demonstration purpose only.
    // Doing this will greatly affect performance.
    setScrollTop(e.target.scrollTop);
  }

  return (
    <>
      {`ScrollTop: ${scrollTop}`}

          Scroll Me

    </>
  )
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Here is a working demo in code sandbox: https://codesandbox.io/s/react-functional-component-event-listener-demo-fmerz?fontsize=14

A: You should add and remove the eventlistener in the same useEffect-call. For instance:
import React, { useEffect } from 'react';

const Component = (props) => {

  useEffect(() => {
    function handleScroll() {
      const scrollTop = window.scrollY;
      console.log(scrollTop);
    }

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  return (

  );
}

A: import React, { useEffect } from 'react';

const Component = (props) => {
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
  });
  useEffect(() => {
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  function handleScroll() {
    let scrollTop = window.scrollY;
  }

  return ()
}


text:
Q: How to handle incoming TCP message and send a response in Node-RED? Using Node-RED TCP socket nodes, is there any way to handle incoming messages when the flow is acting as a TCP socket server (TCP out) that sends data to connected clients?
The idea is to allow a "is alive?" method.

A: The TCP-out node can be set to "Reply" mode which when linked to a TCP-in node in "Server" mode will accept incoming connections and allow you to reply.
The following example just echo's the input back to the client.

[{"id":"ef432e3f1a0f275e","type":"tcp in","z":"cc3f50ef2f39f8d0","name":"","server":"server","host":"","port":"8889","datamode":"stream","datatype":"utf8","newline":"\\n","topic":"","base64":false,"tls":"","x":270,"y":160,"wires":[["825896b40c7c96b9","d24c5bbd4d73d2af"]]},{"id":"825896b40c7c96b9","type":"debug","z":"cc3f50ef2f39f8d0","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":410,"y":200,"wires":[]},{"id":"d24c5bbd4d73d2af","type":"tcp out","z":"cc3f50ef2f39f8d0","name":"","host":"","port":"","beserver":"reply","base64":false,"end":false,"tls":"","x":530,"y":160,"wires":[]}]


text:
Q: How to execute a update query in spark sql temp tables I am trying the below code but it is throwing some random error that I am unable to understand:
df.registerTempTable("Temp_table")

spark.sql("Update Temp_table set column_a='1'")

A: Currently spark sql does not support UPDATE statments. The workaround is to use create a delta lake / iceberg table using your spark dataframe and execute you sql query directly on this table.
For iceberg implementation refer to :
https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-format-iceberg.html


text:
Q: meaning of trenchantly in this sentence I'm not sure what "trenchantly" means in this sentence:

While the rest of the firm gradually acquired a new persona, mortgages remained more trenchantly the same.

Here is the definition I found of trenchant:

*

*vigorous or incisive in expression or style.
  "she heard angry voices, not loud, yet certainly trenchant"

*archaicliterary
  (of a weapon or tool) having a sharp edge.

Thanks for the help!

A: Although one of the meanings of trenchantly is "vigorously, energetically," which by  some stretch might fit the context, I suspect the author thought that trenchant had a lot more to do with a word with a similar root: entrenched. Beyond this etymological connection, however, the two words have nothing to do with one another.
Trenchant ultimately derives from Old French trenchant, present participle of trenchier, to cut. Today, if someone is Paris wants to slice up a chicken or roast, they use the verb trancher. Thus the metaphoric cutting and incisive character of trenchant.
Entrench, though from the same root, didn't follow the same route into the language. It is a native English word derived from trench, i.e., something dug (cut) into the ground, especially for defensive purposes. An entrenched position is defensive and unmoving, "dug in" for battle.
Thus while other departments gradually changed, mortgages didn't move at all, but maintained an entrenched position, remaining the same.


text:
Q: Simplify each coefficient of coefficientlist individually and automatically substitute any repeats I have a 13x13 polynomial coefficient list that I create with:
    CoefficientList[Expand[myequation] /. Equal -> Subtract,{x,z}]

I would now like to simplify each coefficient and to automatically replace repeats (e.g. automatic substitution)
For example, let's say two of my coefficents are:
a*b^2*c^2 and d*b^2*c
I would like mathematica to detect b^2*c as a repeat and automatically substitute it with a new variable
Which commands do I need to look up for this?
Edit: each coefficient is as summation of multiplicative terms, each weighted with a number


text:
Q: whats wrong with this c++ piece of code? In this piece of code, in every iteration of while loop, a line is read from a file. The line is something like:
13,4636137,29464742,29464746,995560164
for every number specified in bold, the existence of that number as a key in a std::map is checked in a for loop. If the key exists, then the value is appended to the string. Then the string is written to the file.
If one of keys not exist in the map, then for that line nothing should be written to the file. (bool is_points_in_range)
But in practice, in the cases that the last point (outside of for loop) is not in key list, the program logic performs well.
Why the boolean operator does not change in for loop?
vector<string> res;
ifstream infile;
map<string, string> m;
while(infile.getline(buffer, LINE_BUFFER_LEN))
{
    line=string(buffer);
    res = SplitBySep(line, ",");
    bool is_points_in_range=true;
    string geo_file_line;
    for (int i=2;i<res.size()-1;i++){
        if ( m.find(res[i]) == m.end() ) {
            is_points_in_range=false;
            break;
        } else {
            geo_file_line= geo_file_line.append(m[res[i]]).append("^");
        }
    }
    if ( m.find(res[res.size()-1]) == m.end() ) {
        is_points_in_range=false;
    } else {
        geo_file_line= geo_file_line.append(m[res[res.size()-1]]).append("\n");
    }
    if (is_points_in_range){
        fprintf(fp_geo, "%s",geo_file_line.c_str());
    }
}

A: res.size()-1 is extremely dangerous. res.size() is an unsigned type, and subtracting one from it when res.size() is 0 is going to give you a very large unsigned integer due to wraparound.
So your program is essentially undefined when res is unpopulated.
I'm amazed your compiler didn't warn you. Do you have warnings switched off?

A: It looks like
    m.find(res[i]) == m.end()
is never true.
Are you sure that this table is fulled properly? res[i]

A: It is better to ask that why this conditional statement does not work well?
We know that for obtaining that a key exists in a std::map, we can use:
if ( m.find("f") == m.end() ) {
    // not found
} else {
    // found
}

as indicated in this question.
But for
map<string, string> m;

this statement does not work well. I dont have any 29464742 key (I am sure), but when I search for this key the else part is executed. Also when I use m.count('29464742') , 1 is returned. I don't know why?
I corrected my code with this conditional statement:
if ( m["f"] == "" ) {
    // not found
} else {
    // found
}

This works for me and my problem is solved.


text:
Q: Can't detect locations in AS3 using compare operators I have made 5 "endzones" on the top of the screen except they aren't being detected at all. After the zone is taken, it is locked out.
The functions like safeX() make the xsafe variable equal to 1 so they will stop working after they are taken, but only last row is tracing. They are predetermined locations so it should be working, but it always skips to the last "else". I have no idea what to change about this code, it works elsewhere in the program but not here:
if (-5 > man.x && man.x > 25) {
    if (onesafe == 0) {
        safeOne();
        trace("1 done")
    } else {
        deadMan();
        trace("1 full")
    }
} else if (55 > man.x && man.x > 85) {
    if (twosafe == 0) {
        safeTwo();
        trace("2 done")
    } else {
        deadMan();
        trace("2 full")
    }
} else if (115 > man.x && man.x > 145) {
    if (threesafe == 0) {
        safeThree();
        trace("3 done")
    } else {
        deadMan();
        trace("3 full")
    }
} else if (175 > man.x && man.x > 205) {
    if (foursafe == 0) {
        safeFour();
        trace("4 done")
    } else {
        deadMan();
        trace("4 full")
    }
} else if (235 > man.x && man.x > 265) {
    if (fivesafe == 0) {
        safeFive();
        trace("5 done")
    } else {
        deadMan();
        trace("5 full")
    }
} else {
    deadMan();
    trace("last row");
}

This is in Action Script 3

A: It skips to the last else because all of the conditions are impossible. I think you have some of your > and < signs backwards.
For example, in the first if, you check if -5 > man.x, or if man.x is less than -5. You then check if man.x > 25. This variable cannot be less than -5 and greater than 25 at the same time.
Perhaps you meant to say if (-5 < man.x && man.x < 25).
A clearer way to write this would be if (man.x > -5 && man.x < 25). It makes it easier to see errors such as this when you put the variable before the constant in a comparison.


text:
Q: How can I compare date in my database in jsp? all,
I am a newbie in jsp, here is my code,
String strArrivaldate = request.getParameter("txtArrivaldate");
// ...connection code....
String strcheck =
    "SELECT  *  FROM tblReservation where Dt_ArrivalDate >= "+ strArrivaldate;

Dt_ArrivalDate is a Date field in my access database...
Anyhow its giving me error in comapring dates, tell me if either way to solve...
Please, Thanks in Advance :)

A: Try:
String strcheck =
  "SELECT * FROM tblReservation where Dt_ArrivalDate >= cdate('"+ strArrivaldate +"')";

If does't work, post your error message here...


text:
Q: How can I make multiple timeouts behind one another? I want to show three messages behind one another always with 1 sec delay:
request.upload.addEventListener('progress',function(e){
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("first message");
    }, 1000);
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("second message");
    }, 1000);
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("third message");
    }, 1000);
}

But I on my screen it displays only "third message".

A: Just use longer delays on the second two, perhaps 1000, 2000, and then 3000.
Example:

var $form = $("form");
$("input").on("click", function(e){
    var percent = 50; // dummy var
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("first message");
    }, 1000);
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("second message");
    }, 2000);
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html("third message");
    }, 3000);
});
.progress-bar {
  display: inline-block;
}
<input type="button" value="Click Me">
<form>

</form>

That said, whenver you find yourself repeating the exact same code with just a small variation, it's an opportunity to refactor. For instance:
["first message", "second message", "third message"].forEach(function(msg, index) {
    setTimeout(function() {
        $form.find('.progress-bar').width(percent+'%').html(msg);
    }, 1000 * (index + 1));
});

Note we're using the index (0, 1, 2) plus one to multiply the timeout, so they appear successively.
Example:

var $form = $("form");
$("input").on("click", function(e){
    var percent = 50; // dummy var
    ["first message", "second message", "third message"].forEach(function(msg, index) {
        setTimeout(function() {
            $form.find('.progress-bar').width(percent+'%').html(msg);
        }, 1000 * (index + 1));
    });
});
.progress-bar {
  display: inline-block;
}
<input type="button" value="Click Me">
<form>

</form>

A: Put each timeout inside the previous one, or better yet, use setInterval!
Something like this is much more manageable:
var messages = ['first', 'second', 'third'];
var index = 0;
var interval = setInterval(function(){
  if (index >= messages.length) {
    clearInterval(interval);
  }
  $form.find('.progress-bar').width(percent+'%').html(messages[index]);
  index++;
}, 1000);

setInterval works similar to setTimeout, except that it repeats the callback method instead of calling it once. The one thing to keep in mind is that you need to clear the interval otherwise it will run forever.


text:
Q: Entering ubuntu without Nvidia graphic card drivers I have an old vaio with win 7 and ubuntu 14.04, with a NVIDIA Geforce 8400M.
Now the screen is a mess with squares and lines both in ubuntu and windows. I think the graphic card is broken.
By entering in windows safe mode I was able to unistall Nvidia drivers and now I can enter windows without any problems (I think due to the use of the native intel graphic card).
I want to do a similar thing for ubuntu. What can I do in order to use ubuntu without the nvidia graphic card?
Thanks a lot.

A: Ok I've found a way.
First I've tried the first solution from this topic without success. Then I've tried this other solution but I've had problems with apt-get due to impossibility to writing in /var/cache/apt/.
In the end I mixed the two solutions. In summary:
Boot with a LiveCD
Mount Ubuntu root partition, change XY accordingly:
sudo mount /dev/sdXY /mnt

Mount some partitions:
sudo mount --bind /dev /mnt/dev
sudo mount --bind /proc /mnt/proc
sudo mount --bind /sys /mnt/sys

Change root directory to the mounted Ubuntu partition:
sudo chroot /mnt

Last, from the 2nd link, remove nvidia drivers:
sudo apt-get remove --purge nvidia-*
sudo apt-get install ubuntu-desktop
sudo rm /etc/X11/xorg.conf
echo 'nouveau' | sudo tee -a /etc/modules

This works great for me, Ubuntu works perfect with low impact on graphics


text:
Q: How to load a pdf file in ipad using sencha? How to load a pdf file in ipad using sencha?
I have tried the following methods:
 html:'
' +
            '' +
               '
'

and
 html:'
' +
            '' +
               '
'

and
html:'
' +
       '<embed type="application/pdf" width="100%" height="100%" src="resources/pdfFiles/help.pdf" />
'

and
  html:'<object data="resources/pdfFiles/help.pdf" TYPE="application/x-pdf" width="100%" height="100%" </object>'

iframe works fine in chrome browser and opens up the pdf. But in ipad it opens up blank. img tag opens up only the first page of the pdf in ipad. How to load the entire pdf in ipad on tap of a button? Any help appreciated.

A: As far as I know, Sencha Touch applications do NOT work well with iframe, especially when pdf is embedded in it.
You had better open up as a new link in browser and let the browser do the remaining tasks.
Here is a discussion on official forum: Displaying PDF and other non-HTML content in Sencha Touch 2


text:
Q: Pandas - Remove leading Zeros from String but not from Integers I currently have a column in my dataset that looks like the following:

Identifier

09325445

02242456

00MatBrown

0AntonioK

065824245

The column data type is object.
What I'd like to do is remove the leading zeros only from column rows where there is a string. I want to keep the leading zeros where the column rows are integers.
Result I'm looking to achieve:

Identifier

09325445

02242456

MatBrown

AntonioK

065824245

Code I am currently using (that isn't working)
def removeLeadingZeroFromString(row):
    if df['Identifier'] == str:
        return df['Identifier'].str.strip('0')
    else:
        return df['Identifier']

df['Identifier' ] = df.apply(lambda row: removeLeadingZeroFromString(row), axis=1)

A: One approach would be to try to convert Identifier to_numeric. Test where the converted values isna, using this mask to only str.lstrip (strip leading zeros only) where the values could not be converted:
m = pd.to_numeric(df['Identifier'], errors='coerce').isna()
df.loc[m, 'Identifier'] = df.loc[m, 'Identifier'].str.lstrip('0')

df:
  Identifier
0   09325445
1   02242456
2   MatBrown
3   AntonioK
4  065824245

Alternatively, a less robust approach, but one that will work with number only strings, would be to test where not str.isnumeric:
m = ~df['Identifier'].str.isnumeric()
df.loc[m, 'Identifier'] = df.loc[m, 'Identifier'].str.lstrip('0')

*NOTE This fails easily to_numeric is the much better approach if looking for all number types.
Sample Frame:
df = pd.DataFrame({
    'Identifier': ['0932544.5', '02242456']
})

Sample Results with isnumeric:
  Identifier
0   932544.5  # 0 Stripped
1   02242456

DataFrame and imports:
import pandas as pd

df = pd.DataFrame({
    'Identifier': ['09325445', '02242456', '00MatBrown', '0AntonioK',
                   '065824245']
})

A: Use replace with regex and a positive lookahead:
>>> df['Identifier'].str.replace(r'^0+(?=[a-zA-Z])', '', regex=True)
0     09325445
1     02242456
2     MatBrown
3     AntonioK
4    065824245
Name: Identifier, dtype: object

Regex: replace one or more 0 (0+) at the start of the string (^) if there is a character ([a-zA-Z]) after 0s ((?=...)).


text:
Q: ERROR - Inferred type is not general enough I am trying to write a simple higher order function in Haskell which takes two arguments:

*

*A list of functions of any type.

*A list of (Numbers or Strings or Boolean, etc) --> any type

The function should apply all the functions in the first list to all the elements in the the second list, store the values in a list, and return the list. An example of the program is:
Main> apply [(^2),(^3),(^4)] [2..8]
--result: --[4,8,9,16,25,27,32,36,49,64,81,125,128,216,256,343,512,625,1296,2401,4096]

The type of the function must be:
apply :: Ord u => [v->u]->[v]->[u]

To do that I've used two helper functions and used recursion. My program is this:
apply :: Ord u => [v->u]->[v]->[u]
apply p s = myApply p s []              --line 59--

myApply :: Ord u => [v->u]->[u]->[u]->[u]
myApply f_list num_list starterlist
    | null f_list = starterlist
    | otherwise = myApply (tail f_list) (num_list) ( applyList (head     f_list) num_list starterlist )

applyList :: Ord u => (v->u)->[u]->[u]->[u]
applyList f num_list starterlist
    | null num_list = starterlist
    | otherwise = applyList f (tail num_list) ( (head num_list) :     starterlist )

I get the error:
ERROR "Lab2.hs":59 - Inferred type is not general enough
*** Expression    : applyList
*** Expected type : Ord a => (b -> a) -> [a] -> [b] -> [a]
*** Inferred type : Ord a => (a -> a) -> [a] -> [a] -> [a]

Any idea what is wrong the with types?

A: The reason why you get this error is because there are conflicting type signatures:
apply :: Ord u => [v->u]->[v]->[u]
apply p s = myApply p s []              --line 59--

myApply :: Ord u => [v->u]->[u]->[u]->[u]
myApply f_list num_list starterlist
    | null f_list = starterlist
    | otherwise = myApply (tail f_list) (num_list) ( applyList (head     f_list) num_list starterlist )
As you can see, the apply function immediately calls the myApply function. Since myApply has signature [v -> u] -> [u] -> [u] -> [u], it means that apply can only have signature [v->u] -> [u] -> [u].
A quick fix is to generalize both myApply and myApplyList to [v -> u] -> [v] -> [u] -> [u]. Now the compile will also detect an error you've made in your applyList function: you forgot to call f on the head num_list. So you can fix it and obtain the following code:
apply :: Ord u => [v->u]->[v]->[u]
apply p s = myApply p s []              --line 59--

myApply :: Ord u => [v->u]->[v]->[u]->[u]
myApply f_list num_list starterlist
    | null f_list = starterlist
    | otherwise = myApply (tail f_list) (num_list) ( applyList (head     f_list) num_list starterlist )

applyList :: Ord u => (v->u)->[v]->[u]->[u]
applyList f num_list starterlist
    | null num_list = starterlist
    | otherwise = applyList f (tail num_list) ( (f (head num_list)) :     starterlist )
Nevertheless, this code is quite unelegant and uses way to many functions and arguments. You can replace it entirely with a single list comprehension:
apply :: [v -> u] -> [v] -> [u]
apply fs xs = [f x | f <- fs, x <- xs]

Based on your comment you also have to sort the values later in the process, you can do this by using the sort :: Ord a => [a] -> [a] builtin:
-- sorting variant
apply :: Ord u => [v -> u] -> [v] -> [u]
apply fs xs = sort [f x | f <- fs, x <- xs]
This generates the required result:
Prelude Data.List> (\fs xs -> sort [f x | f <- fs, x <- xs]) [(^2),(^3),(^4)] [2..8]
[4,8,9,16,16,25,27,36,49,64,64,81,125,216,256,343,512,625,1296,2401,4096]

A: Variation on a theme: taking into Willem's comment indicating that this is a pretty convoluted code (making it difficult to analyze) I'd start with a simpler code, without stating any types at all, to first get a simple working case (that is, a function that produces the expected output), still using a helper function, and recursion:
apply fs     []  = []
apply []     xs  = []
apply (f:fs) xs  = (helper f xs) ++ (apply fs xs)

helper f []     = []
helper f (x:xs) = f x : helper f xs

Then I would ask the Haskell compiler to give me information about what type signature it inferred:
*Main> :t apply
apply :: [t1 -> t] -> [t1] -> [t]

By realizing that t1 -> t maps to your v->u, I can see that the type signature can also be written as:
[v -> u] -> [v] -> [u]

Doing the similar for helper, you will end up with the following:
apply :: [v->u] -> [v] -> [u]
apply fs     []  = []
apply []     xs  = []
apply (f:fs) xs  = (helper f xs) ++ (apply fs xs)

helper :: (v -> u) -> [v] -> [u]
helper f []     = []
helper f (x:xs) = f x : helper f xs

From here, you can work your way by adding Ord constraint, and build up sorting functionality, etc.


text:
Q: Crashing: Attempted to read or write protected memory c# We have a periodic crashing problem with our software. I think I have tracked down where it is happening but I am unfamiliar with the code. It's extremely difficult to debug.
We cannot reproduce this problem on our development environment, it happens on our live environment. The users log in to our system with swipe cards, the terminals have magnetic swipe readers. It happens maybe once a day when they swipe a card. The MSR is read like a keyboard.
I have swiped a card a few hundred times in a row on different occasions and have had no issues on dev.
There is try catch but it doesn't catch anything, the error we are getting in event viewer is:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Here is the function I am pretty sure it's crashing in:
    private void GetRawInputInfo(
        IntPtr rawInputHeader,
        ref IntPtr deviceHandle,
        ref bool handled,
        ref StringBuilder buffer)
    {
        try
        {
            uint cbSize = 0;
            IntPtr hRawInput;

            hRawInput = rawInputHeader;

            if (UnsafeNativeMethods.GetRawInputData(
                hRawInput,
                Structures.RAWINPUTDATAUICOMMAND.RID_INPUT,
                IntPtr.Zero,
                ref cbSize,
                (uint)Marshal.SizeOf(typeof(Structures.RAWINPUTHEADER))) == 0)
            {
                IntPtr ptr = Marshal.AllocHGlobal((int)cbSize);

                if (ptr != IntPtr.Zero &&
                    UnsafeNativeMethods.GetRawInputData(
                        hRawInput,
                        Structures.RAWINPUTDATAUICOMMAND.RID_INPUT,
                        ptr,
                        ref cbSize,
                        (uint)Marshal.SizeOf(typeof(Structures.RAWINPUTHEADER))) == cbSize)
                {

                    Structures.RAWINPUT raw = (Structures.RAWINPUT)Marshal.PtrToStructure(ptr, typeof(Structures.RAWINPUT));

                    deviceHandle = raw.header.hDevice;
                    handled = raw.header.dwType == Structures.RAWINPUTDEVICEDWTYPE.RIM_TYPEKEYBOARD &&
                        raw.keyboard.Message == Messages.WM_KEYDOWN;

                    if (handled)
                    {
                        byte[] state = new byte[256];

                        // Force the keyboard status cache to update
                        UnsafeNativeMethods.GetKeyState(0);

                        // Note: GetKeyboardState only returns valid state when
                        // the application has focus -- this is why we weren't
                        // getting shift keys when the application was not focused
                        if (UnsafeNativeMethods.GetKeyboardState(state))
                        {
                            //StringBuilder unmanagedBuffer = new StringBuilder(64);

                            if (UnsafeNativeMethods.ToUnicode(
                                raw.keyboard.VKey,
                                raw.keyboard.MakeCode,
                                state,
                                buffer,
                                64,
                                0) <= 0)
                            {
                                buffer.Remove(0, buffer.Length);
                            }
                        }
                    }
                }
                if (ptr != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(ptr);
                }
            }
        }
        catch (Exception e)
        {
            BLog.LogError("Error running: GetRawInputInfo()" + e.Message);
        }
    }

Any help or pointers (pun intended) in the right direction would be appreciated,
Thanks
----Updated:
Here is the call stack if this helps in any way:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.RunDialog(Form form)
at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
at System.Windows.Forms.Form.ShowDialog()
at MyApplication.UI.BaseDisplay.ShowDialog(SecurityData security, Int32 listViewState, Nullable`1 ticketId, Int32 currentSeatPosition)
I have made the changes as per Matt and will see if there is any change in the crashing but it may take a day or 2. Sometimes it doesn't crash every day, but generally there is one every day.

A: If the application were to throw an exception somewhere between Marshal.AllocHGlobal((int)cbSize) and Marshal.FreeHGlobal(ptr) you could end up with some memory issues eventually causing your application to crash expectantly.
To remedy the situation I would recommend declaring the IntPtr ptr above the first if statement and then after your catch block use the finally block to check that the ptr variable isn't null and then call Marshal.FreeHGlobal(ptr).
While this may or may not solve your issue, It would be a good idea to ensure that the memory is ALWAYS de-allocated.
Code would look as follows
private void GetRawInputInfo(
        IntPtr rawInputHeader,
        ref IntPtr deviceHandle,
        ref bool handled,
        ref StringBuilder buffer)
    {
        try
        {
            uint cbSize = 0;
            IntPtr hRawInput;
            IntPtr ptr;

            hRawInput = rawInputHeader;

            if (UnsafeNativeMethods.GetRawInputData(
                hRawInput,
                Structures.RAWINPUTDATAUICOMMAND.RID_INPUT,
                IntPtr.Zero,
                ref cbSize,
                (uint)Marshal.SizeOf(typeof(Structures.RAWINPUTHEADER))) == 0)
            {
                ptr = Marshal.AllocHGlobal((int)cbSize);

                if (ptr != IntPtr.Zero &&
                    UnsafeNativeMethods.GetRawInputData(
                    hRawInput,
                    Structures.RAWINPUTDATAUICOMMAND.RID_INPUT,
                    ptr,
                    ref cbSize,
                    (uint)Marshal.SizeOf(typeof(Structures.RAWINPUTHEADER))) == cbSize)
            {

                Structures.RAWINPUT raw = (Structures.RAWINPUT)Marshal.PtrToStructure(ptr, typeof(Structures.RAWINPUT));

                deviceHandle = raw.header.hDevice;
                handled = raw.header.dwType == Structures.RAWINPUTDEVICEDWTYPE.RIM_TYPEKEYBOARD &&
                    raw.keyboard.Message == Messages.WM_KEYDOWN;

                if (handled)
                {
                    byte[] state = new byte[256];

                    // Force the keyboard status cache to update
                    UnsafeNativeMethods.GetKeyState(0);

                    // Note: GetKeyboardState only returns valid state when
                    // the application has focus -- this is why we weren't
                    // getting shift keys when the application was not focused
                    if (UnsafeNativeMethods.GetKeyboardState(state))
                    {
                        //StringBuilder unmanagedBuffer = new StringBuilder(64);

                        if (UnsafeNativeMethods.ToUnicode(
                            raw.keyboard.VKey,
                            raw.keyboard.MakeCode,
                            state,
                            buffer,
                            64,
                            0) <= 0)
                        {
                            buffer.Remove(0, buffer.Length);
                        }
                    }
                }
            }
        }
    }
    catch (Exception e)
    {
        BLog.LogError("Error running: GetRawInputInfo()" + e.Message);
    }
    finally
    {
        if (ptr != IntPtr.Zero)
            Marshal.FreeHGlobal(ptr);
    }
}

A: This is a bit late, but I have had this exact issue with the ToUnicode function in C#. We never did figure out how to make the function work without crashing randomly, so we avoid it like the plague.


text:
Q: Inserting unknown number of rows into a MySQL database I'm writing an online application form and one of the pieces of data I'm trying to collect is the users education history; school name, school city, years they were there and achievements while there.  This data could be collected for anywhere between zero to about four different schools and the user will be dynamically adding more fields if required.
My question is how would this be captured within the database since I don't know how many schools the user will be adding?  Can it be done in one table, or do I need to create multiple tables and capture the education data in a separate table?
Any help or pointers would be greatly appreciated.
Thanks.

A: You need separate tables. One with a row per person, and another with a row per school. Schools can be related to people using either a personID in the school table, or an additional table representing the "person attended school" relationship.
Any association of one entity (person) with multiple other entities (schools) requires more than one table.A general rule to follow is one table per "entity", plus additional tables for many-to-many relationships.

A: Make a separate table for education, and model an "education" in php as a separate class.

A: The term for this is Normalization.  You want to structure multiple tables such that one row of data is succinct, and as little information is repeated as possible.  This can be done by figuring out in your head which pieces of information will be repeated, and making a table for that information.
Data between tables is linked via primary keys (hopefully auto increment integers).  In this case, you would have two tables: Student and Education.  The Student table would have 'StudentID, Name, etc' while the Education table would have 'EducationID, StudentID, SchoolName, SchoolCity, SchoolStudentID, etc'.
Note that Student.StudentID would match with Education.StudentID and can be acquired with the following query:
select Student.*, Education.* from Student left join Education on Student.StudentID = Education.StudentID

In fact, this will have 'SchoolName' and 'SchoolCity' repeating over and over, so this is not fully normalized.  To continue, you need to change it a little bit again:
Student: StudentID, Name, etc
School: SchoolID, SchoolName, SchoolCity, etc
Education: StudentID, SchoolID, StudentSchoolID, etc

Note: each student has a different student id at each school they attend - don't confuse this with the auto increment integer 'StudentID'.  To get a list in this case:
select Student.*, Education.StudentSchoolID, School.* from
  Student left join Education on Student.StudentID = Education.StudentID
  left join School on Education.SchoolID = School.SchoolID


text:
Q: Can we use user input to assign variables in Julia? ans=readline(stdin)

function g(n)
if ans==a
return 1
else
return n
end

This is my code but the readline function only takes strings and i want it to take an expression which i can use in my function. What i want is to assign an expression (a) for variable ans.

A: You could try something like this:
julia> function check(x)
           ans = readline()
           val=Main.eval(Meta.parse(ans))
           println("val == $x :", val==x)
       end;

julia> check(5)
2+3
val == 5 :true

Remarks:

*

*Your functions should not reference global variables (like ans in your example) - if you need to get the value of ans - pass it as parameter.

*Parsing the expression is unsafe - a user might want for an example use this functionality to delete your data. Use with care! In some scenarios you might want for an example to use regular expressions to validate user's input.


text:
Q: SweetAlert html option not working Sweet alert with html option is not working can you guys explain me to solve this.or otherwise i want to bind template explicitly to sweet alert.
    swal({
        title: "Are you sure?",
        text: '<b>Hiiii</b>' ,
        type: "info",
        showCancelButton: true,
        confirmButtonColor: "#F44336",
        confirmButtonText: "Yes, accept it!",
        closeOnConfirm: true
        html:true
    }, function() {
        $scope.onComment(record);
    });

Can you people help me to solve this sweet alert problem?

A: as Doc says :
html is no longer used. Instead use the content object.

(https://sweetalert.js.org/guides/)
try:
swal({
  content: "input",
});

A: I found out how to do it in the new Version.
Please see the information below.
sweet-alert display HTML code in text


text:
Q: How does Ditto's transform work against a raid boss? When Ditto uses transforms in a battle, the answer provided on this question says

It appears that as far as CP is concerned, Ditto simply takes on the base attack, stamina and defense stats of the Pokémon that it transforms into. These values, along with the Ditto's individual values, are plugged into the CP formula.

The formula and calculations are also provided as well.
This works for regular gym battles against other trainer's Pokémon, however raid bosses have anywhere between 8,000 - 25,000 CP with IVs that are probably higher than anything a gym will hold.
How does Ditto's transform ability work when fighting a raid boss?

A: Information in this thread indicates that Dittos behave against raid bosses just as they would against regular gym defenders. That is, the Ditto will pick up the Attack and Defense IVs of the raid boss and convert its CP accordingly. However, it will not increase its HP stat or its level, so it will likely just be a sort of glass cannon, depending on what it transformed into. The reason that raid boss Pokémon have such high CP is due to them being buffed to a level impossible to actually attain as a player, which a Ditto wouldn't copy.

Just saw my first raid and went for it even though it was an easy difficulty level. Croconaw, CP5207. Ditto transformed into him and didn't even faint as myself and another trainer's Jolteon defeated it in 27 seconds. My Ditto was CP1270 after using transform, but was surprisingly able to weather two Crunches and a few Scratches. (A 96%, L28.0 Croconaw is CP1270, by the way—same level and IVs as my Ditto, Blob Loblaw. I still feel like there's something else at play, since he was able to survive two Charge moves.)

In other words, Ditto isn't completely useless in raid battles, since it will likely have a high defense against the raid boss (turning into a Venusaur whose Solar Beam is now 4x ineffective against a transformed Ditto, etc, but exact opposite situation if transforming into Dragonite (weak against its own typing)), but since a transformed Ditto retains its HP, it likely won't last too long in battle.


text:
Q: python generating numbers in modulus i need to iteratively generate number x, which follow these conditions

*

*(x^z) mod n * x < n

*n is known, z changes in every cycle

i need it because I'm implementing timing attack on RSA, and it's needed to generate such number to measure time without modular reduction
Thanks.

A: If the list of z values is not known in advance you could probably try coroutine for this:
def compute_current(x, n, z):
    # some computation here

def crunch(x, n):
    current = x
    z = yield current
    while True:
        current = compute_current(current, n, z)
        z = yield current

c = crunch(x=10)
next(c)

new_x = crunch.send(some_z)
newer_x = crunch.send(some_other_z)
...


text:
Q: Wysiwyg cant detect CKEditor I am downloading modules on Drupal, but I am having trouble with Wysiwyg. It says it needs an editor library, so I downloaded the CKEditor module, which works just fine. When I go into Wysiwyg configuration, however, it keeps telling my that "The version of CKEditor could not be detected. It then says that I should extract the contents so that the library can be found at:
sites/all/libraries/ckeditor/ckeditor.js
I did exactly that, I reset the permissions, I have looked at different installation guides, but nothing seems to work. Do any of you guys know how I can solve this problem?

A: If you are using the latest version of CKEditor, which is version 4, you need to edit the WYSIWYG module of Drupal. The module verifies the editor version using a regular expression which doesn't match with version definition (in javascript) of CKEditor.
You need to modify the wysiwyg/editors/ckeditor.inc file from line 77 to 88 (basically the while loop) with this modified code:
while ($max_lines && $line = fgets($library, 500)) {
  // version:'CKEditor 3.0 SVN',revision:'3665'
  // version:'3.0 RC',revision:'3753'
  // version:'3.0.1',revision:'4391'
  if (preg_match('@version:\"(?:CKEditor )?([\d\.]+)(?:.+revision:\"([\d]+))?@', $line, $version)) {
    fclose($library);
    // Version numbers need to have three parts since 3.0.1.
    $version[1] = preg_replace('/^(\d+)\.(\d+)$/', '${1}.${2}.0', $version[1]);
    return $version[1] . ((isset($version[2])) ? '.' . $version[2] : '');
  }
  $max_lines--;
}

Single quotes has been changed to double quotes in regular expression + the return value adds an extra isset condition.


text:
Q: La función round() no funciona como quiero PHP Estoy tratando de redondear un número con PHP y no obtengo el valor esperado, el número a redondear es:
$valor = 6.3546;

Y debería obtener:
$valor = 6.36;

Estoy usando:
round($valor , 2);

He buscando en la documentación y tampoco funcionan otras opciones. ¿Qué estoy haciendo mal?

A: Prueba hacer esto:
$valor = 6.3546;
round($valor * 100) / 100

Primero lo multiplicamos por 100. Tenemos el valor 635.46; Ahora hacemos el redondeo, puesto que los 0.46 queremos deshacernos de ellos. Haríamos un round(635.46) que devuelve como resultado 635. Por último, a este valor lo dividimos por 100, para recuperar los decimales, lo que nos da 6.36, que es el valor que deseas obtener.

A: Realmente round esta haciendo su trabajo correctamente.
Las 2 reglas básicas del redondeo son:

1º Se escoge el número más cercano que tenga la cantidad de dígitos significativos escogida.
2º Si ambos número más cercanos con la cantidad de dígitos significativos escogidos son igual de cercanos se escoge el que tiene como último dígito significativo un número par (múltiplo de 2)

Por defecto round() utiliza el modo PHP_ROUND_HALF_UP que indica lo siguiente:

PHP_ROUND_HALF_UP: Redondea valor hacia arriba a precisión lugares decimales alejándose de cero, cuando está a medio camino. Hace que 1.5 sea 2, y -1.5 sea -2.

Es decir que si hay las mismas posiciones (distancia) entre los valores mas cercanos redondea al mas lejano de 0.

Ahora revisemos el número 6.3546, los dos valosres mas cercanos de 2 decimales son 6.3500 y 6.3600. Veamos cuál es el mas cercano:
Número | Redondeo | Posiciones
------------------------------
6.3546 | 6.3500   | 46 posiciones
6.3546 | 6.3600   | 54 posiciones

Por lo tanto podemos determinar que el redondeo correcto es 6.35

Ahora bien, si lo que queremos es redondear siempre al alza, por pequeña que sea la fracción podemos apoyarnos en ceil() y pow() y en las matemáticas, un ejemplo:
<?php
// Definimos el valor
$valor = 6.3546;
// Definimos el número de decimales
$precision = 2;
// Multiplicamos el valor por la base decimal (10) elevado al número de decimales(2)
// con esto conseguimos pasar los decimales a la parte entera
$valor = $valor * pow(10, $precision); // 635.46
// Con ceil redondeamos al siguiente entero más alto
$valor =  ceil($valor); //636
// Dividimos el valor por la base decimal (10) elevado al número de decimales(2)
// con esto recuperamos los decimales
$valor = $valor / pow(10, $precision); // 6.36

echo $valor; // 6.36

// Simplificando
$valor = 6.3546;
$precision = 2;
echo ceil($valor * pow(10, $precision)) / pow(10, $precision);

Mas ejemplos
<?php
$valor = 6.3546;
echo ceil($valor*100)/100; //6.36

$valor = 6.35000001;
echo ceil($valor*100)/100; //6.36

$valor = 6.35;
echo ceil($valor*100)/100; //6.35


text:
Q: How to reuse a linq expression for 'Where' when using multiple source tables Let's have the following:
public interface IOne {
    UInt64 Id { get; }
    Int16 Size { get; }
}

public interface ITwo {
    UInt64 OneId { get; }
    Int16 Color { get; }
}

As explained here the way to reuse a linq expression is to write something like this:
public static Expression<Func<IOne, bool>> MyWhereExpression( int value ){
    return (o) => (o.Size > value);
}

int v = 5;
IQueryable<IOne> records = from one in s.Query<IOne>()
                                        .Where(MyWhereExpression(v))
                           select one;

When I want to do the same with two tables I encounter a problem.
The expression:
public static Expression<Func<IOne, ITwo, bool>> MyWhereExpression2(int color ) {
    return (one,two) => (one.Id == two.OneId) && (two.Color > color );
}

Linq 1:
int color = 100;
IQueryable<IOne> records = from one in s.Query<IOne>()
                           from two in s.Query<ITwo>()
                                        .Where(MyWhereExpression2(color))
                           select one;

This doesn't work as .Where sticks to only the 2nd from.
Linq 2:
int color = 100;
IQueryable<IOne> records = (from one in s.Query<IOne>()
                            from two in s.Query<ITwo>()
                            select new { one, two })
                           .Where(MyWhereExpression2(color));

This results in

Argument 2: cannot convert from 'Expression<System.Func<IOne,ITwo,bool>>'
                                    to 'System.Func<AnonymousType#1,int,bool>'

I understand the error message about the AnonymousType, but I cannot figure out how to write the query.
The reason why I want to use an expression rather than just write
where (one.Id == two.OneId) && (two.Color > color )

directly in the linq query is because I want to reuse this expression in multiple linq queries.

A: There may be a more elegant solution that escapes me at the moment, but you could just use Tuple<IOne, ITwo> instead of the anonymous type:
static Expression<Func<Tuple<IOne, ITwo>, bool>> MyWhereExpression2(int color) {
    return t => (t.Item1.Id == t.Item2.OneId) && (t.Item2.Color > color);
}

int color = 100;
IQueryable<IOne> records = (from one in s.Query<IOne>()
                            from two in s.Query<ITwo>()
                            select Tuple.Create(one, two))
                            .Where(MyWhereExpression2(color))
                            .Select(t => t.Item1);

UPDATE: I probably answered too quickly above as that won't work with Linq to SQL since the call to Tuple.Create cannot be translated to SQL. To work with Linq to SQL, the only solution I see at the moment is to create a named type:
class Pair
{
    public IOne One { get; set; }
    public ITwo Two { get; set; }
}

static Expression<Func<Pair, bool>> MyWhereExpression2(int color) {
    return p => (p.One.Id == p.Two.OneId) && (p.Two.Color > color);
}

int color = 100;
IQueryable<IOne> records = (from one in s.Query<IOne>()
                            from two in s.Query<ITwo>()
                            select new Pair { One = one, Two = two })
                            .Where(MyWhereExpression2(color))
                            .Select(p => p.One);

A: First of all why do you have two tables with same set of fields? Ideally database design should avoid same field names in different tables. Design should use inheritance. Common fields should move into base class and EF let's you create table per hierarchy, that should resolve your problem.
If you create your model with Table Per Hierarchy then you will not need interface, and your linq queries can use shared filter expressions.
There is no way to achieve what you are asking unless you sit down and write a complex reflection based method that will clone your expression from one type to another type.

A: Answering my own question...
After some experiments (including Nick Guerrera's original answer) I took another approach - instead of trying to reuse the expression I reuse the whole linq. However, it still required creating a container struct.
struct Pair {
    public IOne One { get; set; }
    public ITwo Two { get; set; }
    public Pair(IOne one, ITwo two) : this() {
        One = one;
        Two = two;
    }
}

public IQueryable<Pair> Get(ISession s, int color) {
            return from one in s.Query<IOne>()
                   from two in s.Query<ITwo>()
                   where (one.Id == two.OneId) && (two.Color > color)
                   select new Pair(one, two);
        }

Now I can call
Get(s, color).Count();

and
var records = (from data in Get(s, color) select data).Take(2000);

etc.


text:
Q: issues in MVC remote validation My code is like this
   public class Payer
{
    public int PayerId { get; set; }
    [Remote("PayerNameExists", "Payer", "Payer name  already exists.", AdditionalFields = "PayerID"), Required]
    public string Name { get; set; }
    public double PatientContribution { get; set; }
}

Inside controller
 public JsonResult PayerNameExists(string Name,int PayerID=0)
{

    var user = db.Payer.Where(x => x.Name == Name.Trim()&&x.PayerId!=PayerID);
    return !user.Any() ?
        Json(true, JsonRequestBehavior.AllowGet) :
        Json(string.Format("{0} is already exists.", Name),
            JsonRequestBehavior.AllowGet);
}

and in view (Edit)
   @Html.TextBoxFor(model => model.Name)

My problem is that inside the function PayerNameExists PayerID always comes as zero I expect to get my model ID out there. Can anyone tell me how I can achieve this?
Note: Data send from client side is liek this

/Payer/PayerNameExists?area=Payer%20name%20%20already%20exists.&Name=ICICIx&PayerID=undefined

A: Your problem is a miss-match in PayerID and PayerId this:
AdditionalFields = "PayerID"

It needs to be this:
AdditionalFields = "PayerId"

And you method needs to be this:
public JsonResult PayerNameExists(string Name,int PayerId=0)

Or change you model to:
public int PayerID { get; set; }

Update
I needed to change the model to PayerID as mentioned above to get this working, not all agree as it was downvoted.
However I also needed to do the following:
Supply an Html.Helper to post the PayerID back i.e. @Html.HiddenFor(model => model.PayerID), otherwise it was going to the default.
If you are having an un-specified error you may want to check the rendered html, it will need to have something like the following:
<input data-val="true" data-val-remote="'Name' is invalid." data-val-remote-additionalfields="*.Name,*.PayerID" data-val-remote-url="/Home/PayerNameExists" data-val-required="The Name field is required." id="Name" name="Name" type="text" value="Name" class="input-validation-error">

Note data-val-remote-additionalfields as this is what jquery needs to render to find the additional properties, if it is different or missing the setting up has failed so check you have references for jquery.validate.js and jquery.validate.unobtrusive.js" also jquery.
The attribute would not work for me, I had to remove the error message. This comes back from the server anyway.
    [Remote("PayerNameExists", "Home", AdditionalFields = "PayerID"), Required]

Also from you rendered link in the update i.e.
/Payer/PayerNameExists?area=Payer%20name%20%20already%20exists.&Name=ICICIx&PayerID=undefined

It is picking up your intended error message as an area route value, so remove it as I mentioned above.
Screen shots


text:
Q: Intent.FLAG_ACTIVITY_CLEAR_TOP in SherlockActivity not serving the purpose The Scenario :
I have four activities : A, B, C and HomeActivity. A is my launcher activity. Am using actionbarSherlock, so A,B and C have menu option in the bar.
The flow is :
 A-> B-> C --**On submit in C**--> HomeActivity

Now when i press Back button on Home Activity, it goes back to activity B as after clicking Submit in C , am using
     Intent intent = new Intent(this, HomeActivity.class);
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );  //Shouldn't this clear A,B and C ??
    //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
    startActivity(intent);
            finish();

But i would like to remain on HomeActivity  only as data is submitted and then it was started.
Also if menu button is pressed on A,B,C, then HomeActivity is started and in that case, i would like to have default behaviour of Back button(i.e go back to activity in which menu was pressed)
Any insights on how to do this as FLAG_ACTIVITY_CLEAR_TOP not serving the purpose!
(P.S. : HomeActivity is not a launcher activity)

A: I think you finish your Home Acitivity while you go to the Home Activity -> Activity A. When you are using clear top flag then your Home Activity should be alive in your stack. Please make sure that you are not finish your Home activity.
And also put this code onKeyDown() method in your Home Activity.
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Log.e("onkeyDown>>>>", "Called>>>>>");
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

check more details check this link:
Other Way
EDIT:
try to put above code into Activity A.
remove finish() method from your code like below:
Intent intent = new Intent(this, HomeActivity.class);
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );  //Shouldn't this clear A,B and C ??
    //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
    startActivity(intent);

And Most Important thing Don't Finish your Activity A launcher
  Activity for Clear top method it should be in stack of Activity remain
  present in your device.

Hope it will solve your problem.


text:
Q: Unable to get the usernames user id for sessions in codeigniter I have a function in my library called getID but I am unable to get it added in my sessions I am not to sure why I can get my username OK
I have sessions Autoloaded
How can I get the user id of the user that is logged in and have it set in the sessions.
public function login() {
if($user_query->num_rows() == 1 ) {
$this->getID = $this->user_id;

$data = array(
'islogged' => true,
'user_id' => $this->user_id,
'username' => $this->CI->input->post('username')
);

$this->CI->session->set_userdata($data);
//$this->CI->db->query("UPDATE " . $this->CI->db->dbprefix . "user SET ip = '" . $this->CI->input->ip_address() . "' WHERE user_id = '" . (int)$this->CI->session->userdata('user_id') . "'");
return true;
} else {
return false;
}

}

public function logout() {
  $this->CI->session->sess_destroy();
}

public function isLogged() {

}

public function getID() {
  return $this->CI->db->get_where('user', array('user_id' => $user_id))->row();
}

A: Just underneath your num_rows(), you have this;
$this->getID = $this->user_id;

If (coming from your question intro), your function to get the users ID is called getID, shouldn't that be the other way round?
$this->user_id = $this->getID();

Edit:
I didn't notice, but Graham is right. You need to pass the variable with the function, although you are also trying to get the user id, using the user id. Try it with the username (I assume these are unique);
      public function getID($username)
      {
                $this->db->select('user_id');
                $this->db->where('username', $username);
                $query = $this->db->get('users');
                if ( $query->num_rows() > 0 )
                {
                          $row = $query->row();
                          return $row->user_id;
                }
                else
                {
                          return false;
                }
      }

...
'user_id' => $this->getID($this->CI->input->post('username'))

Apologise for any syntax errors. I'm replied from my iPhone.

A: $getIDdata = $this->getID($this->user_id);

private function getID($userid) {
    return $this->CI->db->get_where('user', array('user_id' => $user_id))->row();
}

As your function depends on a userid you have to pass it as a variable.

A: I have fixed my own issues after looking at code and thinking more on the subject I now have got it working all I had to do is add $this->user_id = $user_query->row('user_id');
and $this->username = $user_query->row('username'); below the num rows area. and return it in my other function below the login function.
All Working Now I can get the user id number now.
public function login() {
$username = $this->CI->input->post('username');
$password = $this->CI->input->post('password');

$this->CI->db->select('user_id');
$this->CI->db->from('user');
$this->CI->db->where('username', $username);
$this->CI->db->where('password',  hash('sha512', $password));
$this->CI->db->where('status', "1");
$user_query = $this->CI->db->get();

if($user_query->num_rows) {
$this->user_id = $user_query->row('user_id');
$this->username = $user_query->row('username');

$data = array(
'user_id' => $this->user_id
);
$this->CI->session->set_userdata($data);

return true;
} else {
return false;
}

public function getId() {
return $this->user_id;
}

public function getUserName() {
return $this->username;
}