Q: Creating a Spring Boot admin server that also contains Sleuth Dependencies I am developing a Spring Boot Admin Server. When I add Sleuth dependencies (for tracing requests and responses in a distributed architecture), I am getting an exception on startup.
When I comment out the Sleuth dependencies in my POM, the application starts just fine.
The POM
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-sleuth-zipkin</artifactId>
    </dependency>

    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>spring-boot-admin-server</artifactId>
        <version>1.4.1</version>
    </dependency>
    <dependency>
        <groupId>de.codecentric</groupId>
        <artifactId>spring-boot-admin-server-ui</artifactId>
        <version>1.4.1</version>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Camden.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

The main class
import de.codecentric.boot.admin.config.EnableAdminServer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Configuration;

@SpringBootApplication
@Configuration
@EnableAdminServer
public class Application {

public static void main(String[] args) {

    ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
}

}

The full stacktrace
java.lang.IllegalStateException: Error processing condition on org.springframework.cloud.sleuth.instrument.zuul.TraceZuulAutoConfiguration.tracePreZuulFilter
at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:64) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.context.annotation.ConditionEvaluator.shouldSkip(ConditionEvaluator.java:102) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForBeanMethod(ConfigurationClassBeanDefinitionReader.java:178) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitionsForConfigurationClass(ConfigurationClassBeanDefinitionReader.java:140) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(ConfigurationClassBeanDefinitionReader.java:116) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:336) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:246) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:523) ~[spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
at ke.co.teketaxi.sleuthissue.Application.main(Application.java:21) [classes/:na]
Caused by: java.lang.IllegalStateException: @ConditionalOnMissingBean did not specify a bean using type, name or annotation and the attempt to deduce the bean's type failed
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.validate(OnBeanCondition.java:310) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.<init>(OnBeanCondition.java:300) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition.getMatchOutcome(OnBeanCondition.java:112) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.boot.autoconfigure.condition.SpringBootCondition.matches(SpringBootCondition.java:47) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    ... 17 common frames omitted
Caused by: org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanTypeDeductionException: Failed to deduce bean type for org.springframework.cloud.sleuth.instrument.zuul.TraceZuulAutoConfiguration.tracePreZuulFilter
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.addDeducedBeanTypeForBeanMethod(OnBeanCondition.java:373) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.addDeducedBeanType(OnBeanCondition.java:347) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.<init>(OnBeanCondition.java:294) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    ... 19 common frames omitted
Caused by: java.lang.NoClassDefFoundError: org/springframework/cloud/context/named/NamedContextFactory
    at java.lang.ClassLoader.defineClass1(Native Method) ~[na:1.8.0_101]
    at java.lang.ClassLoader.defineClass(ClassLoader.java:763) ~[na:1.8.0_101]
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) ~[na:1.8.0_101]
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:467) ~[na:1.8.0_101]
    at java.net.URLClassLoader.access$100(URLClassLoader.java:73) ~[na:1.8.0_101]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:368) ~[na:1.8.0_101]
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362) ~[na:1.8.0_101]
    at java.security.AccessController.doPrivileged(Native Method) ~[na:1.8.0_101]
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361) ~[na:1.8.0_101]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_101]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_101]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_101]
    at java.lang.Class.getDeclaredMethods0(Native Method) ~[na:1.8.0_101]
    at java.lang.Class.privateGetDeclaredMethods(Class.java:2701) ~[na:1.8.0_101]
    at java.lang.Class.getDeclaredMethods(Class.java:1975) ~[na:1.8.0_101]
    at org.springframework.util.ReflectionUtils.getDeclaredMethods(ReflectionUtils.java:612) ~[spring-core-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:524) ~[spring-core-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.util.ReflectionUtils.doWithMethods(ReflectionUtils.java:510) ~[spring-core-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.boot.autoconfigure.condition.OnBeanCondition$BeanSearchSpec.addDeducedBeanTypeForBeanMethod(OnBeanCondition.java:360) ~[spring-boot-autoconfigure-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    ... 21 common frames omitted
Caused by: java.lang.ClassNotFoundException: org.springframework.cloud.context.named.NamedContextFactory
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_101]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_101]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331) ~[na:1.8.0_101]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_101]
    ... 40 common frames omitted

2016-10-09 11:59:30.432  INFO [-,,,] 2352 --- [           main] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5c33f1a9: startup date [Sun Oct 09 11:59:28 EAT 2016]; root of context hierarchy
2016-10-09 11:59:30.434  WARN [-,,,] 2352 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception thrown from LifecycleProcessor on context close

java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@5c33f1a9: startup date [Sun Oct 09 11:59:28 EAT 2016]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:416) [spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:997) [spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:956) [spring-context-4.3.3.RELEASE.jar:4.3.3.RELEASE]
    at org.springframework.boot.SpringApplication.handleRunFailure(SpringApplication.java:818) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:326) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1186) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1175) [spring-boot-1.4.1.RELEASE.jar:1.4.1.RELEASE]
    at ke.co.teketaxi.sleuthissue.Application.main(Application.java:21) [classes/:na]

A: I added the spring-cloud-starter-zuul dependency and the application started
<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>


Q: Typing Vuex actions I am using Vue3 and Vuex4 with TS.
Let's say my actions look like this in Vuex:
 anAction: async (
    { commit, state }: { commit: Commit; state: MyStoreState },
    { parameter1, parameter2 }: { parameter1: string, parameter2: number }
  ) => {
    /* some code */
    commit("...", /* so on so forth */);
  },

I am using mapActions inside my components to use those actions:
/* rest of component code */
methods: {
    ...mapActions(['anAction'])
}

However, if I call this.anAction from any of my component code, this is its signature:
(...args: any[]) => Promise<any>

Is there a way to get the correct typing on the mapped action, i.e. the one I defined in my store?


Q: config and settings component for C# I'm starting to design a config and settings component for an application.
I need an easy way to read dictionary style settings and also a way to store simple arrays into a persistence level.
is there a commonly used component already available ? (something like log4net for logging)
what options should I look into ?

A: You don't really need to do that: .NET BCL already has everything you need.

A: Take a look at App.Config and the ConfigurationManager class.

A: If you expand the Properties folder in the SolutionExplorer you should find a Settings.Settings item. Double clicking on this will open the settings editor. This enables you to declare and provide initial values for settings that can either be scoped to the application or the current user. Since the values are persisted in Isolated storage you do not need to worry about what privileges the user is executing under.
For a wee example:
I created a new string setting with the name Drink and a TextBox named drinkTextBox. The code to assign the current value to the text box is:
drinkTextBox.Text = Properties.Settings.Default.Drink;

and to update the value persisted:
Properties.Settings.Default.Drink = drinkTextBox.Text;
Properties.Settings.Default.Save();

A: Depending on how flexible you want it to be, you can use the build in Settings designer (go to Project Properties > Settings) and you can add settings there.
These are strongly typed and accessible through code.
It has built in features like Save, Load and Reload

A: We'll often create a sealed class that has a number of properties that wrap calls to the the System.Configuration.ConfigurationManager class.  This allows us to use the standard configuration managagement capabilities offered by the class and the app/web.config file but make the data very easy to access by other classes.
For example we might create a property to expose the connection string to a database as
public static string NorthwindConnectionString
{
  get{return ConfigurationManager.ConnectionStrings["Northwind"].ConnectionString
}

While it creates a wrapper around one line of code, which we usually try to avoid, it does make certain confiuration properties accessible via intellisense and provides some insullation around changes to the location of underlying configuration data.  If we wanted to move the connection string to the registry, we could do so without major impact to the application.
We find this most helpful when we have larger teams or when we need to hand off code from one team to another.  It keeps people from needing to remember what the various settings were named in the config files and even where configuration information is stored (config file, database, registry, ini file, etc.)

A: For noddy apps I use appSettings. For enterprise apps I usually create some custom config sections. CodeProject has some excellent articles on this.
For your scenario of key/value pairs I'd probably use something like this.

A: Building a dictionary in the standard settings
Using the standard Settings, it isn't possible to store dictionary style settings.
To emulate the System.Collections.Specialized.StringDictionary,
what I've done in the past is used two of the System.Collections.Specialized.StringCollection typed settings (this is one of your options for the setting type).
I created one called Keys, and another called values. In a class that needs these settings I've created a static constructor and looped through the two StringCollections and built the StringDictionary into a public static property. The dictionary is then available when needed.
public static StringDictionary NamedValues = new StringDictionary();
public static ClassName() // static construtor
{
  StringCollection keys = Properties.Settings.Default.Keys;
  StringCollection vals = Properties.Settings.Default.Values;
  for(int i = 0; i < keys.Count(); i++)
  {
     NamedValues.Add(keys[i], vals[i]);
  }
}


Q: Both Webmin & ISPConfig won't work on my Ubuntu Linode I followed the steps on this page to download and setup Webmin on my Linode Ubuntu server, however, when I try to visit https + my.ip.add.ress + :10000, the page just hangs and nothing loads. I already looked into my firewall settings.
I uninstalled Webmin and installed ISPConfig and all its dependencies, and the same thing happens at https + my.ip.add.ress + :8080.
This is my first time managing a server so there could be something I overlooked. But my server is a pretty vanilla Ubuntu 12.10 with LAMP stack installed exactly as per the instructions in Linode's documentation.

A: I was able to get ISPConfig 3 deployed, by following these instructions: The Perfect Server - Ubuntu 12.04 LTS (nginx, BIND, Dovecot, ISPConfig 3)

A: Did you perhaps setup a firewall? if so, be sure to add an exception to the firewall.rules to allow sniffing on port 10000


Q: How to install C++ lib Duckx? I want to use this lib DuckX. I followed tutorial,
git clone https://github.com/amiremohamadi/DuckX.git
cd DuckX
mkdir build
cd build
cmake ..
cmake --build .

It went on without any error. However, when I entered sample directory and execute g++ sample1.cpp -lduckx, it got the following error message,
sample1.cpp:1:10: fatal error: duckx.hpp: No such file or directory
 #include "duckx.hpp"
          ^~~~~~~~~~~
compilation terminated.

I wonder how I can successfully use this lib. Could you please tell me what I can do to make the program use this lib. Thanks.


Q: When resuming music player then music resumes but not the play and pause button states Below  is the  code  which   I use.By this code the background  music plays on all activities.But when  I come  back to this activity using  home  button  then music plays normally but the drawables will not resumed. That Mean if music is played and I went  back to that  activity  via  home  button then  play  button is shown  rather than the pause button but I want that if music played on resume then button is pause and if not then show play button.
Can you tell  what to do with  play  and pause  buttons on resuming  activties?
public class RadioActivity extends ActionBarActivity implements RadioListener{

private final String[] RADIO_URL = {"url "};
private ActionMenuView amvMenu;

ImageButton mButtonControlStart;
TextView mTextViewControl;
RadioManager mRadioManager = RadioManager.with(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_radio);
    mButtonControlStart = (ImageButton) findViewById(R.id.buttonControlStart);

    mRadioManager.registerListener(this);
    mRadioManager.setLogging(true);

    initializeUI();
    mButtonControlStart.setBackgroundResource(R.drawable.play);
    Toolbar toolbarBottom = (Toolbar) findViewById(R.id.toolbar);
    toolbarBottom.setTitle("Radio");
    amvMenu = (ActionMenuView) toolbarBottom.findViewById(R.id.amvMenu);
    amvMenu.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
        //  toolbarBottom.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

        public boolean onMenuItemClick(MenuItem item) {
            switch(item.getItemId()){
                case R.id.activity_aboutus:
                    // TODO
                    Intent intent=new Intent(RadioActivity.this,Contact_us.class);
                    startActivity(intent);
                    break;
                // TODO: Other cases
                case R.id.menu_refresh:
                    // TODO
                    Intent intent1=new Intent(RadioActivity.this,Web.class);
                    startActivity(intent1);
                    break;
                case R.id.menu_about:
                    Intent intent2=new Intent(RadioActivity.this,Song_rqst.class);
                    startActivity(intent2);
                    break;
                case R.id.menu_item_share:
                    Intent intent3=new Intent(RadioActivity.this,Ratee.class);
                    startActivity(intent3);
                    break;

            }
            return true;
        }
    });

  }

public void initializeUI() {
    mButtonControlStart = (ImageButton) findViewById(R.id.buttonControlStart);
    mTextViewControl = (TextView) findViewById(R.id.textviewControl);

    mButtonControlStart.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!mRadioManager.isPlaying()) {
                mRadioManager.startRadio(RADIO_URL[0]);
                mButtonControlStart.setBackgroundResource(R.drawable.end);
            }
            else {
                mRadioManager.stopRadio();
                mButtonControlStart.setBackgroundResource(R.drawable.play);

            }
        }
    });

}

@Override
protected void onResume() {
    super.onResume();
    mRadioManager.connect();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    mRadioManager.disconnect();
}

@Override
public void onRadioLoading() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //TODO Do UI works here.
            mTextViewControl.setText("RADIO STATE : LOADING...");
        }
    });
}

@Override
public void onRadioConnected() {

}

@Override
public void onRadioStarted() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //TODO Do UI works here.
            mTextViewControl.setText("RADIO STATE : PLAYING...");
        }
    });
}

@Override
public void onRadioStopped() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            //TODO Do UI works here
            mTextViewControl.setText("RADIO STATE : STOPPED.");
        }
    });
}

@Override
public void onMetaDataReceived(String s, String s1) {
    //TODO Check metadata values. Singer name, song name or whatever you have.
}

@Override
public void onError() {

}

A: Whenever you come back to your Music Play Activity Oncreate() is not called so your drawable resource load on Onpause() or Onstart(), Everytime Oncreate() is not calling.


Q: Sort elements to specified data-* order I have a list of items in a
:

 Pierce

 Annie

 Jeff

 Abed

 Britta

Actually, the list is much longer with real data, but bear with me. As you can see, the
 elements are listed in numerical order. However, I need to rearrange them to fit a specified order in an array:
Array(2, 3, 1, 5, 4)

How do I do this? If sorted by the array above, the elements should be like the following:

 Annie

 Jeff

 Pierce

 Britta

 Abed

This seems simple, but I've looked up every jQuery method in the book and I can't figure out how to do this. Thanks a ton for any help in advance.
Further Clarification:
The specified order is dynamic. However, the elements are always initially listed in numerical order.

A: Iterate through the array starting at index 1. Then append that item after its preceding element. That's it.
http://jsfiddle.net/jT8Tt/
var order = [2, 3, 1, 5, 4];

for (var i = 1; i < order.length; i++) {
    $('li[data-number="' + order[i] + '"]').insertAfter($('li[data-number="' + order[i - 1] + '"]'));
}

Or in slightly more readable format
for (var i = 1; i < order.length; i++) {
    var curElem = $('li[data-number="' + order[i] + '"]');
    var prevElem = $('li[data-number="' + order[i - 1] + '"]');
    curElem.insertAfter(prevElem);
}

A: This is going to be a bit rough since I'm not sure of your overall process but I'll give you the gist and you can implement it.
If the key is predefined...
var sort_order = ['2', '3', '1', '5', '4']
$.each(sort_order function(key,value){

   // build you list here you can use the value from your sort_order
  // to match the data-number and print them out in the order of your choosing.
  // this will work if you dynamically create the sort_order as well.
});

The $.each function will work through the sort_order array allowing you to define an order.

A: A little late, but I'd already written this so it seems a shame to waste it:
var newOrder = ['2', '3', '1', '5', '4'],
    $ul = $("ul"),
    $lis = $ul.children().remove();

$.each(newOrder, function(key,val){
    $ul.append($lis.filter('[data-number="' + val+ '"]'));
});

Demo: http://jsfiddle.net/zgD3n/


Q: add viewbag list of string to checkboxes I have a variable listSiteGroup that contains list of strings, and I put it in ViewBag
ViewBag.listSiteGroup = listSiteGroup;

how do I show each of my string to checkboxes?

I want to show it to the user like this
[ ]sitegroup 1
[ ]sitegroup 2
[ ]sitegroup 3
[ ]sitegroup 4

currently, I looped using for to each viewbag and put it in checkboxfor like the code below
@for (int i = 0; i < ViewBag.listSiteGroup.Count(); i++ )
{
     @Html.CheckBoxFor(ViewBag.listSiteGroup[i].IsEnabled, new {nama=ViewBag.listSiteGroup[i].nama })
}

I'm new to asp.net mvc, I just assume this is how I access each of the viewbag


Q: Introduction images in android app How to make activity which shows introduction images when android app is launched for the first time?
I have 4  images that describe the app. So I want those images to show up when the app runs for the first time and user can swipe from one image to the next in order to unblock working part of the app.

A: For checking if app is lunched first time use SharedPreferences and for displaying images you have to use Bitmap, because without it you will get memory errors.
Add this code in your activity class.(Not in onCreate method)
public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

After in your onCreate method check if app lunched first time and add images to imageView widget.
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
            .getBoolean("isFirstRun", true);

    if (isFirstRun) {

    ImageView imageView = (ImageView) findViewById(R.id.imageView);
    ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);

    imageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.drawable.image1,350,350));
    imageView2.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.drawable.image2,350,350));

        getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
                .putBoolean("isFirstRun", false).commit();

    }

A: Save a flag in sharedPreferences the first time you access the tutorial, then check it on launch.
If no flag:
LauncherActivity -> TutorialActivity (shows four images) save flag -> MainActivity

If flagged:
Launcher Activity -> MainActivity

Check android dev guide for sharepreferences help.
Also Im not sure what you mean about showing during installation. If you mean during loading, then just go ahead and display the images during loading?

A: This is called Appintro. Which runs first time when app launches
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    public boolean isFirstStart;
    Context mcontext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                //  Intro App Initialize SharedPreferences
                SharedPreferences getSharedPreferences = PreferenceManager
                        .getDefaultSharedPreferences(getBaseContext());

                //  Create a new boolean and preference and set it to true
                isFirstStart = getSharedPreferences.getBoolean("firstStart", true);

                //  Check either activity or app is open very first time or not and do action
                if (isFirstStart) {

                    //  Launch application introduction screen
                    Intent i = new Intent(MainActivity.this, MyIntro.class);
                    startActivity(i);
                    SharedPreferences.Editor e = getSharedPreferences.edit();
                    e.putBoolean("firstStart", false);
                    e.apply();
                }
            }
        });
        t.start();

    }
}

http://www.viralandroid.com/2016/10/android-appintro-slider-example.html
http://www.androidhive.info/2016/05/android-build-intro-slider-app/
https://github.com/apl-devs/AppIntro


Q: ¿Cómo mantener a un servidor escuchando un puerto? Estoy implementando un servidor FTP basandome en la informacion del siguiente enlace:
https://www.codeproject.com/Articles/380769/Creating-an-FTP-Server-in-Csharp-with-IPv-Support
Siguiendo este tutorial, no sé que poner en la clase principal para hacer que el servidor se mantenga conectado durante un tiempo indeterminado escuchando en puerto 21 para recibir las solicitudes.
He intentado ciclar con un while el servidor, pero solo me ha provocado errores. Disculpen si mi pregunta es muy noob pero realmente soy nuevo en esto.
Les agradezco su atención.

A: Puedes usar la clase TcpListener. Aquí tienes un ejemplo: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener(v=vs.110).aspx
Este es el código:
public static void Main()
  {
    TcpListener server=null;
    try
    {
      // Set the TcpListener on port 13000.
      Int32 port = 13000;
      IPAddress localAddr = IPAddress.Parse("127.0.0.1");

      // TcpListener server = new TcpListener(port);
      server = new TcpListener(localAddr, port);

      // Start listening for client requests.
      server.Start();

      // Buffer for reading data
      Byte[] bytes = new Byte[256];
      String data = null;

      // Enter the listening loop.
      while(true)
      {
        Console.Write("Waiting for a connection... ");

        // Perform a blocking call to accept requests.
        // You could also user server.AcceptSocket() here.
        TcpClient client = server.AcceptTcpClient();
        Console.WriteLine("Connected!");

        data = null;

        // Get a stream object for reading and writing
        NetworkStream stream = client.GetStream();

        int i;

        // Loop to receive all the data sent by the client.
        while((i = stream.Read(bytes, 0, bytes.Length))!=0)
        {
          // Translate data bytes to a ASCII string.
          data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
          Console.WriteLine("Received: {0}", data);

          // Process the data sent by the client.
          data = data.ToUpper();

          byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

          // Send back a response.
          stream.Write(msg, 0, msg.Length);
          Console.WriteLine("Sent: {0}", data);
        }

        // Shutdown and end connection
        client.Close();
      }
    }
    catch(SocketException e)
    {
      Console.WriteLine("SocketException: {0}", e);
    }
    finally
    {
       // Stop listening for new clients.
       server.Stop();
    }

    Console.WriteLine("\nHit enter to continue...");
    Console.Read();
  }


Q: Crash :Critical failure: the LastResort font is unavailable in ios7 Iam inserting the contacts from the address book in to the sqlite3 database. for only some contacts my app is getting crashed at
sqlite3_finalize(statement)

this statement. and this is happening in ios7. The crash log is as follows

"Critical failure: the LastResort font is unavailable. in ios"

NSString *insertSQL = [NSString stringWithFormat:@"insert into vcards (some thing data)",(something data)];
const char *insert_stmt = [insertSQL UTF8String];
      sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL);
      if (sqlite3_step(statement) == SQLITE_DONE)
      {
         NSLog(@"Record inserted");
      }
      else {
           NSLog(@"Record inserted failed");
        }
      sqlite3_finalize(statement);
    sqlite3_close(database);

please any one suggest me how to fix this crash.

A: This has nothing to do with your contacts but to do with the fonts when transitioning from ios 6 to ios 7. Delete all the fonts in your project and then carefully add one by one to your .plist testing each time before adding the next until you find the one that is causing the problem.
Have a look at this post from someone who also had the same problem as you and the person's answer.
Person have the same problem as you


Q: How can I write fun, cool, and challenging integration problems? I just asked this question on another site but with only a handful of somewhat helpful responses.
I just made the following integral problem which I think is very cool and nice, but I don't know how to solve it. (I found it by taking the derivative which is what you see here.)
$\int \left(\frac{x^2-2}{x^3+6x} \right)^2 dx$. (I won't tell you the answer.)
Once I had obtained this nice looking derivative and turned it into a nice looking integration problem I wanted to make more such problems, but the functions I was deriving didn't really seem to have challenging nor interesting derivatives.
How can I come up with some fun integration problems (definite or indefinite)? I should also mention that my knowledge of calculus does not include complex analysis such as the Residues things or the contour theorems, only basic Calc 2 level stuff (eg. taylor series, integration by parts, integration tables from my physics textbook as I don't know where my calculus one is.)


Q: ReferenceError: Function Not Defined. What am I missing? Can't seem to figure out why I keep getting this ReferenceError: OnLoad is not defined error.
Since the time of my previous commit, I have changed lines 28-30 and that is all.
How can this cause my javascript to not be loaded properly? I have only changed these three lines. I'm certain these lines shouldn't really be related. The Javascript file is identical to the one in the previous commit.
What am I missing?
UserInterface.php - Current Commit
class UserInterface {
    var $ParentAppInstance;
    function __construct($AppInstance){
        $this->ParentAppInstance = $AppInstance;
        $this->DrawPageHTML();
        $this->DrawDBSetDropdown();
        $this->DrawQueryForm();
     }

//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
    $CurrDB_Obj = $this->ParentAppInstance->CurrentDBObj; //Line 28
    $EncodedFields = json_encode($CurrDB_Obj->GetFields()); //Line 29
    echo ""; // Line 30
    echo '
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">

    ';

}

protected function DrawDBSetDropdown(){
    echo '
';
        echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
        $i = 0;
        foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
            if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
                echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
            }
        }

        foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
            if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
            else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
            else{
                //Add the DBSet to the dropdown list.
                $i++;
                echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
            }
        }
        echo '</select>';
    echo '
';

}

protected function DrawQueryForm(){
    echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
        echo '
';
        $NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
        for ($i = 1; $i <= $NumActiveQBoxes; $i++){
            echo '
';
                echo '<select name=Field_' . $i . '">';
                    $DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
                    $CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
                    foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
                        //echo $Field;
                        echo '<option>' . $Field . '</option>';
                    }
                echo '</select>';
                echo '<input type="text" name="Query_' . $i . '"></input>';
                echo '<button class= "RMButton" type="button">-</button>';
            echo '
';
        }
        echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
        echo '<button type="submit" id="submit">SEARCH</button>';
    echo '</Form>';

    echo '';

}

UserInterface.php - Previous Commit
class UserInterface {
var $ParentAppInstance;
function __construct($AppInstance){
    $this->ParentAppInstance = $AppInstance;
    $this->DrawPageHTML();
    $this->DrawDBSetDropdown();
    $this->DrawQueryForm();
}

//Override thjis function to change the HTML and PHP of the UI page.
protected function DrawPageHTML(){
    $DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);    //Line 28
    $CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];     //Line 29
    $EncodedFields = json_encode($CurrDBSet_Obj->GetDBSetFields());      //Line 30
    echo "";
    echo '
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
        <link rel="stylesheet" type="text/css" href="./CSS/UserInterface.css">

    ';

}

protected function DrawDBSetDropdown(){
    echo '
';
        echo '<select onchange="SwitchDatabaseSet();" name="DBSetList" form="DBSetSelector" id="DBSetSelector">';
        $i = 0;
        foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
            if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){
                echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
            }
        }

        foreach ($this->ParentAppInstance->DBSetsArr as $DBSet){
            if ($DBSet->DBSetName == $this->ParentAppInstance->CurrDBSetStr){/* DO NOTHING. IE. IGNORE IT*/}
            else if ($DBSet->DBSetName == 'DBSet0'){/* DO NOTHING. IE. IGNORE IT*/}
            else{
                //Add the DBSet to the dropdown list.
                $i++;
                echo '<option value="' . $DBSet->DBSetName . '">' . $DBSet->DBSetName . '</option>';
            }
        }
        echo '</select>';
    echo '
';

}

protected function DrawQueryForm(){
    echo '<form action="DatabaseSearch.php" method="post" accept-charset="UTF-8">';
        echo '
';
        $NumActiveQBoxes = $this->ParentAppInstance->Config['ApplicationSettings']['NumberDefaultQueryOptions'];
        for ($i = 1; $i <= $NumActiveQBoxes; $i++){
            echo '
';
                echo '<select name=Field_' . $i . '">';
                    $DBSet_Num = filter_var($this->ParentAppInstance->CurrDBSetStr, FILTER_SANITIZE_NUMBER_INT);
                    $CurrDBSet_Obj = $this->ParentAppInstance->DBSetsArr[$DBSet_Num];
                    foreach($CurrDBSet_Obj->GetDBSetFields() as $Field){
                        //echo $Field;
                        echo '<option>' . $Field . '</option>';
                    }
                echo '</select>';
                echo '<input type="text" name="Query_' . $i . '"></input>';
                echo '<button class= "RMButton" type="button">-</button>';
            echo '
';
        }
        echo '<button type="button" id="add" onclick="AddQueryBox();">+</button>';
        echo '<button type="submit" id="submit">SEARCH</button>';
    echo '</Form>';

    echo '';

}

UserInterface.js
var DBSetFields = [];
var NumQBoxes = 3;

//window.onload = OnLoad();
function OnLoad(Fields){
    console.log("OnLoad called");
    CloneDBSetFields(Fields);

    var RMNodeList = document.getElementsByClassName('RMButton');
    for (var i = 0; i < RMNodeList.length; ++i) {
        console.log(RMNodeList[i]);
        RMNodeList[i].onclick = RemoveQBox;  // Calling myNodeList.item(i) isn't necessary in JavaScript
    }
}

function JSTEST(){
    window.alert("JS Called Successfully!!");
}

function CloneDBSetFields(Fields){
    console.log("CloneDBSetFields");
    DBSetFields = Fields;

}

function SwitchDatabaseSet(MainPageDoc){
    document.getElementById("DebugOutput").innerHTML = "Test";
    window.location.replace('/GLS_DBSearchProject/index.php?DBSet=' + document.getElementById("DBSetSelector").value);
    console.log(document.getElementById("DBSetSelector").value);
    //console.log(document.)

}

function Fields_FOREACH(ELEMENT, INDEX, ARRAY){
    console.log("TEST");
    var FieldOption = document.createElement('option');
    FieldOption.setAttribute('value', ARRAY[INDEX]);
    FieldOption.innerHTML = ARRAY[INDEX];
    this.appendChild(FieldOption);
}

function AddQueryBox(){
    NumQBoxes += 1;
    var NewQBox = document.createElement('div');
    NewQBox.setAttribute('class', 'QueryBox');

    //Create and fill Field Selector dropdown "select" element
    var FieldSelector = document.createElement('select');
    FieldSelector.setAttribute('name', 'Field_' + NumQBoxes);
    //foreach element in Fields
    console.log(DBSetFields);
    DBSetFields.forEach(Fields_FOREACH, FieldSelector);
    //Create and fill
    var QueryText = document.createElement('input');
    QueryText.setAttribute('type', 'text');
    QueryText.setAttribute('name', 'Query_' + NumQBoxes);

    //Create "-" Remove button for removing query lines.
    var RemoveButton = document.createElement('button');
    RemoveButton.innerHTML = "-";
    RemoveButton.setAttribute('type', 'button');
    RemoveButton.setAttribute('class', 'RMButton');
    RemoveButton.addEventListener("click", RemoveQBox);

    //Combine the individual elements into a new query box and insert the new query box into the HTML Document
    NewQBox.appendChild(FieldSelector);
    NewQBox.appendChild(QueryText);
    NewQBox.appendChild(RemoveButton);
    document.getElementById("QFormBody").insertBefore(NewQBox, document.getElementById("add"));

}

function RemoveQBox(e){
    console.log("Remove");
    var RemoveButton = this; //this == e.currentTarget
    console.log(RemoveButton);
    var QBox = RemoveButton.parentNode;
    QBox.remove();
    NumQBoxes -= 1;
}

EDIT: My Javascript file is not being loaded on the client side (ie. it doesn't show up under "Sources", so I'm not really not sure: Why wouldn't my javascript be loading on the client side?


Q: sql server query with a too "ORs" clauses I have a dictionary container with next info:
{ID=412, CATEG=1},
{ID=413, CATEG=2},
{ID=414, CATEG=3},
{ID=415, CATEG=4}

I need to construct a string query for execute it in SQL SERVER, something like that:
select * from PASSAGES psg
where   (psg.ID = 413 AND psg.CATEGORY_ID = 2)
                OR  (psg.ID = 414 AND psg.CATEGORY_ID = 3)
                OR  (psg.ID = 415 AND psg.CATEGORY_ID = 4)
                OR  (psg.ID = 416 AND psg.CATEGORY_ID = 5)

The problem is that my container now have 4 elements, if it would have 200 i would have 200 ORs ??
Any idea about avoid too many ORs ?  (I need a string query, i can not use a stored procedure)
thanks in advance

A: You could use a join instead, putting the values in a derived table:
select p.*
from passages p join
     (values (413, 2), (414, 3), (415, 4), (416, 5)
     ) v(id, category_id)
     on p.id = v.id and p.category_id = v.category_id;

A: If you can store that dictionary container in a table it will be easier to use it in an (IN) clause like this:
SELECT * FROM PASSAGES AS psg
JOIN Dictionary AS D ON psg.ID = D.ID
WHERE psg.ID IN (D.ID) AND psg.CATEGORY_ID IN (D.CATEG)

and as the Dictionary table records increase the query will be fixed all time without multiple (ORs).


Q: Excel file name changed dynamically I used an excel template. In my ssis package at first the template is copied in the working directory and package execute. In the next run the excel file which is already existed in the working directory it moved into BACKUP folder and again the template file copied. It works good.
But i want to do something when i move it i want to rename it like is the previous file name is Input_01 in the next move it will input_02. How can i do this?
i am using Execute process task toolbox in SSIS pacakge.
and a .bat file is called. in the .bat file i write
         move "E:\InputFolder\Input.xls" "D:\Backup"

         copy "E:\Template\Input.xls" "E:\InputFolder\Input.xls"

I want a ouput in the backup folder the excel files are like
Input_01,Input_02.... what will be my command?

A: Here's how to do it with a batch file:
@echo off
set cnt=1
for /f %%f in ('dir /b "D:\Backup\Input_*.xls"') do set /a cnt+=1
if %cnt% lss 10 (move "E:\InputFolder\Input.xls" "D:\Backup\Input_0%cnt%.xls") else (move "E:\InputFolder\Input.xls" "D:\Backup\Input_%cnt%.xls")
copy "E:\Template\Input.xls" "E:\InputFolder\Input.xls"

You can have more control over your files' naming convention (not to mention deletion of old files) if you use a Script Task, though.

A: can we use a 'File system task' instead. It helps us Renaming a file. You will have to use a 'For-Each loop Container' as well.


Q: Not being able to Load Image from a function To HTML Canvas I am trying to place the screenshot image into html canvas but not being able to. I have taken screenshot of current tab by using following chrome API. Trying to make a chrome extension.
/* background.js */
let id = 100;
//calling chrome api
chrome.browserAction.onClicked.addListener(() => {
    chrome.tabs.captureVisibleTab((screenshotUrl) => {
        const viewTabUrl = chrome.extension.getURL('screenshot.html?id=' + id++)
        let targetId = null;
        //checking if the opened tab id is the same as the target id
        chrome.tabs.onUpdated.addListener(function listener(tabId, changedProps) {
            if (tabId != targetId || changedProps.status != "complete")
                return;
            chrome.tabs.onUpdated.removeListener(listener);
            const views = chrome.extension.getViews();
            for (let i = 0; i < views.length; i++) {
                let view = views[i];
                if (view.location.href == viewTabUrl) {
                    view.setScreenshotUrl(screenshotUrl);
                    return;
                }
            }
        });

        //chrome tabs create method
        //no listener on create event because the tab’s URL may not be set at the time this event is fired
        chrome.tabs.create({ url: viewTabUrl }, (tab) => {
            targetId = tab.id;
        });
    });
});

But not able to call the image from the function
function setScreenshotUrl(url) {
    document.getElementById('target').src = url;
};

var cnv = document.getElementById("conv");

cnv.onclick = function() {
    var x = document.getElementById("target").src;
    document.getElementById("demo").innerHTML = x;
};

window.addEventListener('load', function() {
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    var img = document.getElementById("target");

    ctx.drawImage(img, 10, 10, 300, 175, 0, 0, 100, 175);
});

A: The problem was image was not ready at windows on load event, verified by checking the innerHTML of the image, while if I try to do the same thing in onClick event, the image is successfully loaded into canvas.


Q: How to parse CSV that is passed as a parameter to a method I have a string that contains content of CSV file.
I need to extract those values to my objects.
I don't get CSV from CSV file I receive it as a parameter (data).
And in exmple they use file.csv to parse data.
I have tried to load it in MemoryStream but without luck.
public string methos(string data)
        {
            CsvFileDescription inputFileDescription = new CsvFileDescription
            {
                SeparatorChar = ',',
                FirstLineHasColumnNames = true
            };

            CsvContext cc = new CsvContext();

            MemoryStream mStream = new MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(data));

            IEnumerable<Data datas=
            cc.Read<Data>(mStream, inputFileDescription);

Also I don't know if I pick good framework to parse CSV to custom objects but to me it's important that values can have commas and that framework can handle that.

A: LINQtoCSV only takes a StreamReader, not a stream.  Try this:
        using (MemoryStream mStream = new MemoryStream(System.Text.ASCIIEncoding.Default.GetBytes(data)))
        using (StreamReader reader = new StreamReader(mStream))
        {
            IEnumerable<Data> datas = cc.Read<Data>(reader, inputFileDescription);
        }


Q: A basic question regarding a rational function on a locally Noetherian scheme Let $k$ be a field, $A = k[x,y] / (y^2, xy)$. I know that the ideals $P = (x-1)$ and $Q = (x-3)$ are maximal ideals in A, so $U = $ Spec $A \backslash \{ P, Q \}$ is an open subset of Spec $A$. Then it turns out that
$$
\frac{x-2}{(x-1)(x-3)}
$$
is an element of $\Gamma (U , O_{Spec \ A})$ and it is a rational function.
Could someone please explain me why this is a rational function? (I am reading the explanation in the notes by Ravi Vakil, but I am getting confused. Perhaps I am missing something easy...)
ps I would also appreciate if someone could explain me how this is an element of $\Gamma (U , O_{Spec \ A})$. I am a bit confused about this also.. Thank you!


Q: Linear system control via augmented state space Consider the simple linear system:
$$
\dot{x} = Ax + Bu
$$
We want to identify a $u$ that ensures x converges to a desired value (typically $0$). Usually this is done by choosing some $u = u(x) = Kx$ so that we end up with $\dot{x} = (A-BK)x$, allowing us choose $K$ appropriately. But, we can instead couple $u$ to the dynamics like this:
$$
\begin{bmatrix} \dot{x} \\ \dot{u} \end{bmatrix} = \begin{bmatrix} A & B \\ C & D \end{bmatrix} \begin{bmatrix} x \\ u \end{bmatrix}
$$
Now we can (theoretically) choose $C$ and $D$ to control the eigenvalues. We'd also need to choose a $u(t=0)$, possibly just setting this to $0$. Note that in order for $x=0$ to be a stable fixed point we need $\dot{x} = Bu = 0$, so we'd likely need $u$ to converge to zero as well.
Intuitively, $u$ acts as an integrator for $x$ with gain $C$, and sometimes LTI systems are given these integrating states to help push $x$ to zero when there are disturbances (not included here). From this point of view, the main difference is that the integrating state $u$ can be made to decay as well by setting $D$.
I setup a little experiment with a simple motor model and played around with the values until I got a system where the angle of the motor converged to $0$ (code is below). It seemed to work fine, although it was a bit oscillatory. Here's a plot of that.
I could see this type of model being useful for describing inertia in the input signal $u$.
My questions are as follows:

*

*Has this already been studied? If so, what is it called?

*When is the system controllable?

*How would you go about designing $C$ and $D$?

I haven't been able to find similar questions or articles on this topic, but please let me know if there's something that I missed!
R= 2.0; % Ohms
L= 0.5; % Henrys
Km = .015; % torque constant
Kb = .015; % emf constant
Kf = 0.2; % Nms
J= 0.02; % kg.m^2

A = [
    -R/L   -Kb/L    0   % Current
    0       0       1   % Angle
    Km/J   -Kf/J    0   % Angular rate
];
B = [
    1/L
    0
    0
];
C = [0 140 -30];
D = [-10];

A_ = [
    A, B ;
    C, D
];

f = @(t,z) A_*z;

eigvals = eig(A_)

[t,y] = ode45(f,[0,10], [0;1;0;0]);

clf
plot(t,y)
legend('Current','Angle','Angle rate','Input', 'interpreter', 'latex')
```

A: Your proposed model alteration is essentially adding an integral before the input
$$
\begin{bmatrix}
\dot{x} \\ \dot{u}
\end{bmatrix} =
\underbrace{
\begin{bmatrix}
A & B \\ 0 & 0
\end{bmatrix}}_{\mathcal{A}}
\begin{bmatrix}
x \\ u
\end{bmatrix} +
\underbrace{
\begin{bmatrix}
0 \\ I
\end{bmatrix}}_{\mathcal{B}} v.
$$
In your case you picked $v = C\,x + D\,u$. This is controllable as long as $(\mathcal{A},\mathcal{B})$ is controllable and the matrices $C$, $D$ form a state feedback gain (i.e. choose $\mathcal{K} = \begin{bmatrix}C & D\end{bmatrix}$ such that $\mathcal{A + K\,B}$ is Hurwitz) and one can use different tools to obtain one, such as pole placement or LQR.

A: It looks a lot like the equation for a double dampener, where the force acting ($F\propto \ddot{x})$ is proportional to the velocity $(\ddot{x}\propto\dot{x}$) but for two dampeners connected with a mass at one end and another end variable, for example.


Q: Sort dates in Perl I need help sorting in perl. I have an array of dates in this format. DD-MMM-YY. Example 19-FEB-12.
I have spent quite a lot of time already, but couldn't get it work. I'm very new to perl as well. Any amount of help is appreciated. Thanks!!

A: An easy way is to convert the dates to YYYYMMDD format that can be sorted lexicographically.
Note that MM should be the month represented as a two digit number.

A: You could use the core module Time::Piece to convert the DD-MMM-YY (or any input format) to an ISO 8601 form.  This allows simple sorting.  This example builds up an array of raw data which includes the ISO value as a sort key; sorts it; and returns the data in sorted order:
#!/usr/bin/env perl
use strict;
use warnings;
use Time::Piece;
my $t;
my @data;
while (<DATA>) {
    chomp;
    $t = Time::Piece->strptime( $_, "%d %b %y" );
    push @data, [ $t->datetime, $_ ];    #...ISO 8601 format...
}
my @sorteddata = sort { $a->[0] cmp $b->[0] } @data;
for my $value (@sorteddata) {
    print $value->[1], "\n";
}
__DATA__
19 Feb 12
17 Aug 11
31 Mar 10
01 Aug 11
08 Apr 11
29 Feb 11

A: This can be done using the Time::Piece core module's strptime method to decode the dates and sorting them according to the resulting epoch seconds.
This program demonstrates the idea.
use strict;
use warnings;

use Time::Piece;

my @dates = <DATA>;
chomp @dates;

my @sorted = sort {
  Time::Piece->strptime($a, '%d-%b-%y') <=> Time::Piece->strptime($b, '%d-%b-%y')
} @dates;

print "$_\n" for @sorted;

__DATA__
05-FEB-12
10-MAR-11
22-AUG-11
26-FEB-12
10-NOV-12
07-JUN-11
20-APR-12
19-DEC-12
17-JAN-11
25-NOV-11
28-FEB-11
04-SEP-11
03-DEC-12
16-SEP-12
31-DEC-11
08-JUN-11
22-JUN-12
02-AUG-12
23-SEP-11
14-MAY-11

output
17-JAN-11
28-FEB-11
10-MAR-11
14-MAY-11
07-JUN-11
08-JUN-11
22-AUG-11
04-SEP-11
23-SEP-11
25-NOV-11
31-DEC-11
05-FEB-12
26-FEB-12
20-APR-12
22-JUN-12
02-AUG-12
16-SEP-12
10-NOV-12
03-DEC-12
19-DEC-12

A: Here's a possible way to do this using only basic Perl (no modules):
#! perl -w

use strict;

my @dates = ( '19-FEB-12', '15-APR-12', '13-JAN-11' );

# map month names to numbers
my %monthnum = (
    'JAN' => 1, 'FEB' => 2, 'MAR' => 3, 'APR' => 4,
    'MAY' => 5, 'JUN' => 6, 'JUL' => 7, 'AUG' => 8,
    'SEP' => 9, 'OCT' => 10, 'NOV' => 11, 'DEC' => 12
    );

# sort the array using a helper function
my @sorted_dates = sort { convert_date($a) cmp convert_date($b) } @dates;

print join(", ", @sorted_dates), "\n";
# outputs: 13-JAN-11, 19-FEB-12, 15-APR-12

exit(0);

# THE END

# converts from 19-FEB-12 to 120219, for sorting
sub convert_date
{
    my $d1 = shift;
    my $d2;

    if ($d1 =~ /(\d{2})-([A-Z]{3})-(\d{2})/)
    {
        $d2 = sprintf( "%02d%02d%2d", $3, $monthnum{$2}, $1 );
    }
    else
    {
        die "Unrecognized format: $d1";
    }

    return $d2;
}

This relies on your dates being formatted correctly, but it should be trivial to add more validation.

A: Using DateTime module;
or use sort command with month option (*nix);
or transform dd-mmm-yyyy to yyyymmdd and then sort;

A: Totally from scratch:
Printed Output:
Unsorted:
14-OCT-06
15-OCT-06
13-OCT-06
19-FEB-12
29-DEC-02
15-JAN-02

Sorted (Least recent to most recent):
15-JAN-02
29-DEC-02
13-OCT-06
14-OCT-06
15-OCT-06
19-FEB-12

Code:
#!C:\Perl64

#Input Strings
@inputs = ('14-OCT-06','15-OCT-06','13-OCT-06', '19-FEB-12', '29-DEC-02', '15-JAN-02');

print "Unsorted:\n";
foreach(@inputs){
    print $_."\n";
}

# Hash for Month : Number
%months = ('JAN' => '01',
         'FEB' => '02',
         'MAR' => '03',
         'APR' => '04',
         'MAY' => '05',
         'JUN' => '06',
         'JUL' => '07',
         'AUG' => '08',
         'SEP' => '09',
         'OCT' => '10',
         'NOV' => '11',
         'DEC' => '12');
# Hash for Number : Month
%revmonths = ('01'=>'JAN',
         '02' => 'FEB',
         '03' => 'MAR',
         '04' => 'APR',
         '05' => 'MAY',
         '06' => 'JUN',
         '07' => 'JUL',
         '08' => 'AUG',
         '09' => 'SEP',
         '10' => 'OCT',
         '11' => 'NOV',
         '12' => 'DEC');

# Rearrange the order to 'Year-Month-Day'
@dates = ();
foreach(@inputs){
    my @split = split('-',$_);
    my @rearranged = reverse(@split);
    @rearranged[1] = $months{$rearranged[1]};
    push(@dates, \@rearranged);
}

# Sort based on these three fields
@sorted = sort { $a->[2] <=> $b->[2] } @dates;
@sorted = sort { $a->[1] <=> $b->[1] } @sorted;
@sorted = sort { $a->[0] <=> $b->[0] } @sorted;

# Replace Month Number with Month name
$size = @sorted;
for $counter (0..$size-1){
    my $ref = $sorted[$counter];
    my @array = @$ref;
    my $num = $array[1];
    $array[1] = $revmonths{$array[1]};
    my @array = reverse(@array);
    $sorted[$counter] = \@array;
}

print "\nSorted (Least recent to most recent):\n";
foreach(@sorted){
    my @temp = @$_;
    my $day = $temp[0];
    my $month = $temp[1];
    my $year = $temp[2];
    print $day."-".$month."-".$year;
    print "\n";
}


Q: sort object by key by using lodash but key has lost after sorted I want to sort some Object look likes this
data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
}

I want to sort it by "name".
I tried to use Lodash for this problem.
_.sortBy(data, [function(o) { return o.name; }]);

but, it return me an array of objects without the keys
[
    {
      "name": "Emmy",
      "age": 20
    },
    {
      "name": "Nacky",
      "age": 12
    },
    {
      "name": "Nat",
      "age": 20
    }
]

I want it return me sorted object with key like the same
{
    "vuzPuZUmyT8Z5nE": {
        "name": "Emmy",
        "age": 20
    },
    "imH3i4igFNxM3GL": {
        "name": "Nacky",
        "age": 12
    },
    "OkIPDY1nGjxlq3W": {
        "name": "Nat",
        "age": 20
    }
}

what should I do? thanks

A: Objects in JS can't be sorted, and the order of the properties is not reliable, ie it depends on browsers' implementations. That's why _.sortBy() is converting your object into a sorted array.
I can think of 2 options to work with that.
Add the key to the objects in the array
If you just need an ordered array with the keys in the objects, so you can render a list.

var data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
};

var result = _(data)
  .map(function(v, k) { // insert the key into the object
    return _.merge({}, v, { key: k });
  })
  .sortBy('name') // sort by name
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Create an order array
Create an array of ordered keys, and use them when you wish to render the objects in order.

var data = {
        "imH3i4igFNxM3GL": {
            "name": "Nacky",
            "age": 12
        },
        "vuzPuZUmyT8Z5nE": {
            "name": "Emmy",
            "age": 20
        },
        "OkIPDY1nGjxlq3W": {
            "name": "Nat",
            "age": 20
        }
};

var orderArray = _(data)
  .keys() // create an array of keys
  .sortBy(function(key) { // sort the array using the original names
    return data[key].name;
  }) // sort by name
  .value();

console.log('The order array', orderArray);

console.log(orderArray.map(function(k) {
  return data[k];
}));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

A: I use something like this.

    let data = {
    'g34ghgj3kj': {
        YOUR_KEY: 'g34ghgj3kj',
        'key1': false,
        'key2': false,
    },
    'hh334h664': {
        YOUR_KEY: 'hh334h664',
        'key1': true,
        'key2': false,
    },
    //{...}
};

_.orderBy(data, ['key1', 'key2'], ['desc', 'desc']).reduce((result, value) => {
    result[value.YOUR_KEY] = value;
    return result;
}, {});


Q: Error when adding parameter for reportsviewer VB.Net I am new to VB.NET and I'm trying to add a parameter for filtering a reportsviewer. When I added the Client_Name_, the following error pops up -

How can it be solved? I scoured everywhere for solutions but to no avail.


Q: Can AWS RDS be used as a MySQL host only? Is it possible to use AWS' RDS MySQL solution in tandem with my current file server host? By that, I mean, can I connect to the RDS MySQL server as I am with my hosts current database?
I've tried the AWS documentation but it seems a bit flaky in this area.
Thank you,

A: Amazon RDS is a database server, just like any other. If you start up an RDS MySQL server, you can connect to it from anything else that can connect to a MySQL server.
The difference is that you do not have direct host access to the RDS server. Meaning, you cannot SSH into it and get a command prompt.
But you can connect to it from any MySQL client, including MySQL Workbench.


Q: Is select N + 1 ever better than eager join? i am using nhibernate profiler and seeing  a few places where it is giving me a "Select n + 1" warning.
The obvious fix is to make some upfront eager joins but it got me thinking if in certain cases its actually simpler or faster to live with Select N + 1 compared to doing joins that may be load lots of data that you never actually use.

A: Your thinking is correct. In some cases, for example, all the root entities reference one or two instances of another entity. It might be faster to do 2 or 3 small selects instead of a denormalized one (i.e. with joins)
There is a way to make this convenient in almost all cases: batch-size. If you set this attribute in both the entities and the collections to your usual page size, you'll get a constant number of small selects (one per entity type).

A: Select N+1 will become bigger and bigger problem once your application will have enough data in it.
Generally loading data is much cheaper then another trip to the data base. So if you can - you obviosly should avoid it.
As for loading additional data. If you are thinkg that you will load property values that are not going to be used you can use NHibernate 3.0 lazy loaded property feature.
So overall Select N+1 should be avoided.

A: I am not sure if you know about another option
In your mappings add
<list name="MyItems" batch-size="10">

or
<bag name="MyItems" batch-size="10">

If you have 10 Items, you only need two queries instead of 11. For 20 items, you need
three instead of 21 and so on. This will cut out about 90 percent of your queries.


Q: String not storing in a structure properly typedef struct class {
   char* CLASS_ID;
   char* CLASS_NAME;
}

What would cause those two strings to lose their values over the course of 30-40 unrelated lines of code? (Assigned to a pointer returned from a function called getString()).

A: Perhaps getString() returns a pointer to a statically allocated buffer, whose value is overwritten each time it is called?
Maybe you're overflowing an array and corrupting your stack or heap?
Maybe you're storing a pointer to a string that was allocated on the stack and has gone out of scope?
With some more information about or code for getString(), someone could probably give you a definitive answer.

A: Well, not knowing how getString() is implemented, or any of your other code, it could be anything. That is part of the problem with C's (over)use of pointers.
My first guess would be that getString() actually returns a pointer to an internal (static) string, and thus each call obliterates the value retrieved from the last.
If you are actually using C++, then I would strongly advise you to ditch this code and use std::string instead. I bet your problem magically goes away.

A: Aside from what the other's posted here there's also that you should avoid names like class, CLASS_ID and CLASS_NAME because they are #defined in many librarys you might include in the future and debug for hours to find out what's suddenly wrong.


Q: Relating to the progressive tense Someone started to jump, he was jumping, and he finished jumping, and at intervals, he didn’t do any jumps, so is this situation finally counted as ‘he jumped once’?
Progressive: a verb tense that is used to refer to an action or a state that is continuing to happen
Technically, ‘an action is continuing to happen’ means there is one action. Likewise, we don’t say ‘a person is continuing to exist’ means there are several people. Am I understanding it correctly?


Q: Create AWS cache clusters in VPC with CloudFormation I am creating an AWS stack inside a VPC using CloudFormation and need to create ElastiCache clusters on it. I have investigated and there is no support in CloudFormation to create cache clusters in VPCs.
Our "workaround" was to to create the cache cluster when some "fixed" instance (like a bastion for example) bootstrap using CloudInit and AWS AmazonElastiCacheCli tools (elasticache-create-cache-subnet-group, elasticache-create-cache-cluster). Then, when front end machines bootstrap (we are using autoscaling), they use  elasticache-describe-cache-clusters to get cache cluster nodes and update configuration.
I would like to know if you have different solutions to this problem.

A: VPC support has now been added for Elasticache in Cloudformation Templates.
To launch a AWS::ElastiCache::CacheCluster in your VPC, create a AWS::ElastiCache::SubnetGroup that defines which subnet in your VPC you want Elasticache and assign it to the  CacheSubnetGroupName property of AWS::ElastiCache::CacheCluster.

A: You workaround is a reasonable one (and shows that you seem to be in control of your AWS operations already).
You could improve on your custom solution eventually by means of the dedicated CustomResource type, which are special AWS CloudFormation resources that provide a way for a template developer to include resources in an AWS CloudFormation stack that are provided by a source other than Amazon Web Services. - the AWS CloudFormation Custom Resource Walkthrough provides a good overview of what this is all about, how it works and what's required to implement your own.
The benefit of using this facade for a custom resource (i.e. the Amazon ElastiCache cluster in your case) is that its entire lifecycle (create/update/delete) can be handled in a similar and controlled fashion just like any officially supported CloudFormation resource types, e.g. resource creation failures would be handled transparently from the perspective of the entire stack.
However, for the use case at hand you might actually just want to wait for official support becoming available:

*

*AWS has announced VPC support for ElastiCache in the context of the recent major Amazon EC2 Update - Virtual Private Clouds for Everyone!, which boils down to Default VPCs for (Almost) Everyone.

We want every EC2 user to be able to benefit from the advanced networking and other features of Amazon VPC that I outlined above. To enable this, starting soon, instances for new AWS customers (and existing customers launching in new Regions) will be launched into the "EC2-VPC" platform. [...]
You don’t need to create a VPC beforehand - simply launch EC2
  instances or provision Elastic Load Balancers, RDS databases, or
  ElastiCache clusters like you would in EC2-Classic and we’ll create a
  VPC for you at no extra charge.  We’ll launch your resources into that
  VPC [...] [emphasis mine]

*This update sort of implies that any new services will likely be also available in VPC right away going forward (else the new EC2-VPC platform wouldn't work automatically for new customers as envisioned).

  Accordingly I'd expect the CloudFormation team to follow suit and complete/amend their support for deployment to VPC going forward as well.

A: My solution for this has been to have a controller process that polls a message queue, which is subscribed to the SNS topic which I notify CloudFormation events to (click advanced in the console when you create a CloudFormation stack to send notifications to an SNS Topic).
I pass the required parameters as tags to AWS::EC2::Subnet and have the controller pick them up, when the subnet is created. I execute the set up when a AWS::CloudFormation::WaitConditionHandle is created, and use the PhysicalResourceId to cURL with PUT to satisfy a AWS::CloudFormation::WaitCondition.
It works somewhat, but doesn't handle resource deletion in ElastiCache, because there is no AWS::CloudFormation::WaitCondition analogue for stack deletion. That's a manual operation procedure wth my approach.
The CustomResource approach looks more polished, but requires an endpoint, which I don't have. If you can put together an endpoint, that looks like the way to go.


Q: Area enclosed by polar curve I can't get the text answer using standard method of integration of a polar equation. Yet when I use a symmetry method I do get their answer.  Can you assist in clarification?
Find the area of the region enclosed by $r=4cos(3 \theta)$.
I use $ \frac 12  \int_0^{2\pi} (16cos^2(3\theta) d\theta$.  For $cos^2(3\theta)$ I use the identity $\frac12[1+cos(6\theta)]$
This gives me $\frac{16}{4} \int_0^{2\pi} 1+cos(6\theta) d\theta$.
This gives me $4[\int_0^{2\pi}1 d\theta +\frac16\int_0^{12\pi} cos (u) du]$.
The integral of the cosine term is $0$, so I get $\theta $ evaluated from $0$ to $2\pi$.  This gives me $4(2\pi)=8\pi$.
When I use a symmetrical method A=$6\int_0^{\pi/6}\frac12(16 cos^2(3\theta)d\theta$ I get $4\pi$.   This is the text answer.
Don't understand why my 2 answers don't match.

A: Your first answer is twice the correct answer for the following reason: if you let $\theta$ range from $\theta=0$ to $\theta=2\pi$, the curve $r=4\cos(3\theta)$ — which is a flower with three petals — is traced twice, and therefore you find twice the area. If you trace it carefully starting from $\theta=0$, which is $(4,0)$ in cartesian coordinates, you will see that the curve is completed and comes back to the initial point at $\theta=\pi$; and then, from $\theta=\pi$ to $\theta=2\pi$ you retrace it once more.
In the second method, you find the area of a half of one petal, which you correctly determined to range from $\theta=0$ to $\theta=\dfrac{\pi}{6}$. Since there are six such half-petals, multiplying by $6$ clearly yields the correct answer. Note, however, that taking six half-petals of the same "angular width" (so to speak) as the one going from $\theta=0$ to $\theta=\dfrac{\pi}{6}$ will produce the angle six times as wide, i.e. from $\theta=0$ to $\theta=\pi$, consistent with my explanation above.

A: To provide yet another approach, you can use Green's theorem on the differential form $x \,dy$ to transform the area integral over one petal into a line integral along the petal:
$$\frac13 A = \text{area of petal}  = \int\limits_{\text{petal}}\,1\,dA = \int\limits_{\text{boundary of petal}} x\,dy $$
Since $r = 4\cos(3\theta)$, the petal can be parameterized by
$$(x(\theta), y(\theta)) = (r(\theta)\cos\theta, r(\theta)\sin(\theta)) = (4\cos\theta\cos(3\theta), 4\sin\theta\cos(3\theta))$$
for $\theta \in \left[-\frac{\pi}6, \frac{\pi}6\right]$.
Differentiating gives $dy = (4\cos\theta\cos(3\theta) - 12\sin\theta\sin(3\theta))\,d\theta$ so
$$\frac13 A = \int_{-\frac{\pi}6}^{\frac{\pi}6}4\cos\theta\cos(3\theta) (4\cos\theta\cos(3\theta) - 12\sin\theta\sin(3\theta))\,d\theta = \frac{4\pi}3$$
so $A = 4\pi$.
The integral is a bit cumbersome but it can be solved using the product-to-sum formulas for sine and cosine.


Q: Different datatype from endpoint created a basic Api Rest service in Laravel 4.2 (the project was created in this version), and local responses me corresponding datatype (Int), but when execute endpoint from online server, receive different datatype(String) to local(Int), appreciate someone who knows the reason of this.
Local example
HERE
Online CentOs Server example
HERE


Q: CCButton not working completely when pressed in Cocos2D v3 iOS I have a gameplay scene, over which I add a CCNode as a child. My Game Over node has a replay CCButton in it.
The button is supposed to restart the game play scene. The problem is, when I press the "Restart" button, it goes through the lines but it doesn't perfrom replaceScene. Also it doesn't highlight when pressed. Here's my relevant code:
The code where I add the Game Over Node in my GamePlay Class (.m):
CCNode GameOver = [[GameOverNode alloc] init];

[self unscheduleAllSelectors];
[self stopAllActions];
[[OALSimpleAudio sharedInstance] stopBg];
[[CCDirector sharedDirector] stopAnimation];
[[CCDirector sharedDirector] pause];

[self addChild:GameOver z:5];

and here's the code for GameOver Class (.h):
@interface GameOverNode:CCNode {
 CCButton *_aButton;
}
@property (nonatomic, retain) CCButton *aButton;
- (id)init;
- (void)ButtonPressed:(id)sender;

and Game Over (.m):
-(id)init {
if ( self = [super init] ){

    CCSpriteFrame *replayFrame = [CCSpriteFrame frameWithImageNamed:@"Replay.png"];

    _aButton = [CCButton buttonWithTitle:@"" spriteFrame:replayFrame];
    _aButton.position = ccp(200,200);
    [_aButton setTarget:self selector:@selector(ButtonPressed:)];
    [self addChild:_aButton z:2];
}
return self;
}

- (void)ButtonPressed:(id)sender
{
NSLog(@"Button pressed");
CCTransition* t = [CCTransition transitionFadeWithDuration:0.4f];
t.outgoingSceneAnimated = YES;
t.incomingSceneAnimated = YES;

[[CCDirector sharedDirector] replaceScene:[GamePlayScene scene] withTransition:t];
}

The thing is, it prints out "Button pressed", also goes through the rest of the code of the method, but nothing happens.
I'll appreciate if you can let me know what I am doing wrong.
Thanks!

A: It does not work because you have paused the CCDirector. Remove the following line:
[[CCDirector sharedDirector] pause];

Alternatively if you really need that, resume the director before you attempt to replace the scene.
[[CCDirector sharedDirector] resume];
[[CCDirector sharedDirector] replaceScene:[GamePlayScene scene] withTransition:t];


Q: Actionscript 2.0 How to get keyPress working for number 1 I'm trying to get on (keyPress "<1>") working for my calculator so when I press one, the number one appears in the text box.
But there is no keyPress "<1>" for the number one, I heard there is something called KeyCode is needed, and I found the keycode for 1 is "49".
Can someone write the keyPress for the number 1?

A: Use the Key event listener.
var key:Object = {
    onKeyDown:function() {
        switch(Key.getCode()) {
            case 49:
                trace('key 1 is down');
                break;
            case 50:
                trace('key 2 is down');
                break;
        }
    }
};
Key.addListener(key);

Then you can handle actions in the switch statement.


Q: p5 - Syntax error: expected ; but got hour I have the following code:
function setup() {
    createCanvas(500, 500);
    angleMode(DEGREES);
}
function draw() {
    background(0);
    translate(width/2, height/2);
    let hour = hour();
}

I get an error on let hour = hour(); saying that there was supposed to be a semicolon there instead of hour. The only way I have found to fix the problem is by writing it as let; hour = hour(); This gets rid of the error but then the code doesn't run properly. Any ideas?

A: In JavaScript, variables and functions can't have the same name. (More confusingly: functions are variables!)
So that means that this line:
let hour = hour();

Is not allowed, because you're trying to reassign the hour variable from being a function to being a value. (This is a side effect of using let. If you had used var then this would have silently did the wrong thing.)
To fix the problem, just rename your variable to something that's not already a function.
let myHour = hour();


Q: Syntax highlighting using RSyntaxTextArea library in java netbeans swing Text is highlighted for java syntax when i am doing it in a seperate class i.e.
TextEditorDemo , but not getting the same result when i am executing the code in
action listener of a JCombo Box in swing and initialising the JtextArea msg1 (here) with the rsyntaxtextarea object -> syntax is not being highlighted.
TextEditorDemo.java
import javax.swing.*;
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;

/**
 * A simple example showing how to use RSyntaxTextArea to add Java syntax
 * highlighting to a Swing application.<p>
 */
public class TextEditorDemo extends JFrame {

   public TextEditorDemo() {

      JPanel cp = new JPanel();

      RSyntaxTextArea syntaxTextArea = new RSyntaxTextArea(20, 60);
      syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
      // No other property of RSyntaxTextArea is allowed to use

      // You can now modify textArea object similar to any other JTextArea object to add other functionality
      JTextArea textArea = syntaxTextArea;
      JScrollPane sp = new JScrollPane(textArea);
      cp.add(sp);

      setContentPane(cp);
      setTitle("Text Editor Demo");
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      pack();
      setLocationRelativeTo(null);
   }

   public static void main(String[] args) {
      // Start all Swing applications on the EDT.
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            new TextEditorDemo().setVisible(true);
         }
      });
   }

}

action listener for JComboBox -
private void language1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:

        RSyntaxTextArea syntaxTextArea = new RSyntaxTextArea(6, 20);

        String lang = (String) language1.getSelectedItem();
        syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
        msg1 = syntaxTextArea;
        msg1.setVisible(true);
        System.out.println("language "+lang);
        if (lang.equals("JAVA")) {
            syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
        }
        else if(lang.equals("C")){
            syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_C);
        }
        else if(lang.equals("CSHARP")){
            syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_CSHARP);
        }
        else if(lang.equals("CSS")){
            syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_CSS);
        }

        //syntaxTextArea.setCodeFoldingEnabled(true);*/

    }

A: private void language1ActionPerformed(java.awt.event.ActionEvent evt) {
        RSyntaxTextArea syntaxTextArea = new RSyntaxTextArea(6, 20);

        String lang = (String) language1.getSelectedItem();
        syntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
        msg1 = syntaxTextArea;
        msg1.setVisible(true);

The above code does nothing. You haven't actually added the syntax area component to the frame.
Don't create a new RSyntaxArea object!
Instead you need to make the syntaxTextArea an instance variable in your class then you can reference the variable from the listener and just change the editing style property.
Or if for some reason the class doesn't allow you to dynamically change the property, then you will need to use:
sp.setViewportView(syntaxTextArea);

in you listener code. In which case the scrollpane variable will now need to be an instance variable in your class.
Either way you will need to create an instance variable that can be referenced from your ActionListener so you will need to restructure your code. Read the Swing tutorial on How to Use Text Areas. The demo code there will show you how to better structure your classes.


Q: For loop variable is empty in gmake I have a list of header files created thus:
expand=$(1)/$(1).h
HDRS=$(foreach x, $(DIRS), $(call expand,$(x)))

Which yields a list like a/a.h b/b.h ...
but when I use this in a for loop:
for i in $(HDRS) ; do \
    echo $$i \
    cp $$i $(some_dir) \
done

$$i is empty. And the cp fails, having only one argument.
The usual variants of $$i ( $i, $$i, $(i), ${i} ), don't change anything, nor do the usual variants of $(HDRS) ("$(HDRS)", etc.).
gmake echos the for-loop as
for i in a.h b.h ; \
do \
    echo $i \
    cp $i somedir \
done

Which looks correct.
But the implicit bash shell emits an error "/bin/sh -c: line 5: syntax error: unexpected end of file"
gmake then exits due to the failed command.

A: Due to the \, make emits the recipe as a single line.  This confuses the shell.  Try this instead, using ; in place of the line terminator:
for i in a.h b.h ; \
do \
    echo $i ; \
    cp $i somedir ; \
done


Q: Meteor.js: Understanding sort parameters within a find{} method I am doing exercises in the book "Getting Started With Meteor.js Javascript Framework" and
there is a section where a template called categories is created, then a {#each} loop thumbs through a collection.This is done with the intent of printing the results to the screen. This works and the code is below.
<template name ="categories">

my stuff

        {{#each lists}}

            {{Category}}

        {{/each}}

</template>

My question is this:
In the code below the sort parameter doesn't seem to do anything. I am curious what it is supposed to be doing. I understand that theoretically it's suppose to "sort", but when I play with the parameters nothing changes. I looked it up in the meteor documentation and I couldn't figure it out. I am trying to modify the code so that it so that it sorts in a different order. This way I can see results and get a real understanding of how {sort:  works. I tried modifying the {sort: {Category: 1}}) to {sort: {Category: -1}}) as well as {sort: {Category: 2}}) and it's always the same result.
  Template.categories.lists = function() {
    return lists.find({}, {sort: {Category: 1}});  // Works

  /* return lists.find({}); */                     // Works just the same

  }

The Collections are as follows:
lists.insert({Category:"DVDs", items: [{Name:"Mission Impossible" ,Owner:"me",LentTo:"Alice"}]});

lists.insert({Category:"Tools", items: [{Name:"Linear Compression Wrench",Owner:"me",LentTo: "STEVE"}]});

A: In your code, you can attempt to change the argument of the sort to be an array instead of an object, like this:
sort: [["Category","asc"],["another argument","desc"],[...]]
so the code :
 Template.categories.lists = function() {
    return lists.find({}, {
        sort: [
            ["Category", "asc"],
            ["another argument", "desc"],
            [...]
        ]
    });
    // return lists.find({}); // Works just the same
}

A: As per my understanding that is because default is to sort by natural order. More info can be found at this link


Q: Magento 2 : How to setup an option for customers to buy one year free shipping? I`m a beginner in Magento 2. I did setup a shopping cart app with flat rate shipping. But now client wants to add a link in cart for buying premium membership, so that this particular users can shop without shipping charges for one year. Normal users will have to pay shipping charges as usual. Any idea on how to implement this?

A: You can make a Customer Group.
Stores > Other Setting and select Customer Group.
Add new customer group.
Go To Cart Rule please follow.
Marketing > Select Cart Price Rule > Add New Rule. now without using coupon and select free shipping in magento for that customer group .
Thanks

A: Easiest thing comes to my mind is Coupon code that he'll use everytime, with 1-year validity.


Q: SQL Generate a table of multiple top X records, where top # comes from another table I'm using SQL Server 2012.
I need to generate an output that includes the results for multiple "top" queries, where the # of "top" rows returned in each query varies based on the value in another table.
My first table, call it Table1, is the reference table where NUMBER tells me how many top rows I need to return from another table for each unique MARKET/MEASURE.
MARKET      MEASURE     NUMBER
------      -------      ------
MarketA     MeasureA    411
MarketA     MeasureB    396
MarketB     MeasureA    548
MarketB     MeasureC    424
MarketC     MeasureC    411

The second table, Table2, lists detail for each individual person in a given MARKET/MEASURE, where the combination of MARKET and MEASURE is my primary key.  There are many entries for any given MARKET/MEASURE.
MARKET      MEASURE      LASTNAME      COMPLIANT
------      -------      --------      ---------
MarketA     MeasureA     Coppola       Y
MarketA     MeasureA     Winterbottom  N
MarketA     MeasureB     Scorsese      Y
MarketC     MeasureC     Tarr          Y

For each value in Table1, I need to return that many top rows from Table2 based on a sort of LASTNAME in ascending order.  So for example, because Table1 has a NUMBER of 411 for MarketA/MeasureA, my output needs to contain the TOP 411 * rows from Table2 (based on all persons in that market sorted by LASTNAME ascending), and the TOP 396 rows for MarketA/MeasureB, and then the TOP 548 rows for MarketB/MeasureA, and so on, all in one table, as if I've "UNIONed" (?) each query individually.
How do I do this dynamically without having to UNION individual queries for each MARKET/MEASURE in Table1 (of which there are over 1000)?
I feel like the answer is to use a select expression to generate # in the TOP expression, like.....
select TOP (select NUMBER from TABLE2) *
from TABLE1 t1
inner join TABLE2 t2 on t2.MARKET = T1.MARKET
                     and t2.MEASURE = T2.MEASURE

...but obviously I'm missing a few steps because the TOP expression will bring back multiple values from TABLE2, and I can't quite figure out how to get it to "run" for each MARKET/MEASURE combination.
Help much appreciated.

A: This is what APPLY can be used for
SELECT
    *

FROM
    Table1
    CROSS APPLY
    (
        SELECT TOP (Table1.Number)
            *

        FROM
            Table2

        WHERE
            Table1.Market = Table2.Market
            AND Table1.Measure = Table2.Measure

        ORDER BY
            LastName
    ) AS TopResults

http://sqlfiddle.com/#!6/46b57/4

A: For anyone in the same predicament, I figured out another way of accomplishing the same thing, using the ROW_NUMBER() windowed function instead of trying to use TOP dynamically.  The idea was to add a row number to Table2, partitioned by market & measure and ordered by last name, then to join the Table1.Number to Table2, and select only rows where the row number was less than Table1.Number, thus returning the "top" number of rows according to the Table1.Number.
with temp as (select 'rownum' = row_number() over(partition by t2.market, t2.measure)
                                                  order by t2.lastname)
                , t2.*
                , t1.number
              from table2 t2
              inner join table1 t1 on t1.market = t2.market
                                   and t1.measure = t2.measure)
select *
from temp
where rownum <= number
order by market, measure, rownum


Q: How to connect Verilog module's output to several wires? Say I have a module foo(in1,in2,out); and module mad1(in,out); module mad2(in,out); module mad3(in,out);
While instantiating these modules I want to use the output (out) of foo as an input to each of the mad modules.
Something like this:
input in1,in2;
output out1,out2,out3;
wire w_out;
foo i_foo(.in1(in1),.in2(in2),.out(w_out));
mad1 i_mad1(,in(w_out),.out(out1));
mad2 i_mad2(,in(w_out),.out(out2));
mad3 i_mad3(,in(w_out),.out(out3));

Is that approach correct or should I save the output of the foo module to a register?

A: This approach is perfectly correct.


Q: use where clause to search from a substring SQL Server Hi I have column which contains below values:
names
-----------------
johnDoeKing
Joseph
MaxSecond
Plank
-----------------

Now I have an input string:
johnDoeMaxAlexPaul

is there a way I can use where clause which will return JohnDoeKing and MaxSecond from my column when I search with this input string in where clause ?

A: Yes, you can use LIKE:
DECLARE @InputString VARCHAR(100) = 'johnDoeMaxAlexPaul';

SELECT *
FROM dbo.YourTable
WHERE @InputString LIKE '%' + names + '%';

Here is a live demo of this, and the results are:
╔═════════╗
║  names  ║
╠═════════╣
║ johnDoe ║
║ Max     ║
╚═════════╝


Q: Swipe To Push View Controller Like Whatsapp messages details i want to ask what is the best way we need to work when we want to pan a view to push view controller, we want to make something similar like whatsapp messages status view like the following photo

we try swipe gesture and also pan gesture but we want to make same animation like what happen on whatsapp
so please can you help me?
waiting your responses
thanks