text:
Q: Spring's ConstructorResolver#instantiateUsingFactoryMethod ignoring spring.mongodb.embedded.version for embedded mongodb I'm trying to run a Spring Boot application with an embedded mongodb (not just for testing, but live). It was working fine until I decided to modernize to use latest available Spring jars, etc. Upgrading to Spring Boot 2.6.1 I now get an 'IllegalStateException: Set the spring.mongodb.embedded.version property or define your own MongodConfig bean to use embedded MongoDB' from EmbeddedMongoAutoConfiguration#determineVersion, where my application.properties entry for 'spring.mongodb.embedded.version=3.6.3' is being reported as null. Tracing back to ConstructorResolver#instantiateUsingFactoryMethod I see it passes in an EmbeddedMongoProperties with null 'version'. That method is way over my head but I believe it is the cause. I suspect it's somehow using the older MongoProperties which does not have version but I'm not sure. I've been debugging for hours and I'm not getting anywhere fast. Any help appreciated.
application.properties:
server.port=8090

spring.mongodb.embedded.version=3.6.3
spring.mongodb.embedded.features=SYNC_DELAY,NO_HTTP_INTERFACE_ARG
spring.datasource.driver-class-name=mongodb.jdbc.MongoDriver
#spring.data.mongodb.uri=mongodb://127.0.0.1:27017
spring.data.mongodb.database=jokes
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
#spring.data.mongodb.username=craig
#spring.data.mongodb.password=***
#spring.data.mongodb.authentication-database=admin
spring.mongodb.embedded.storage.database-dir=/home/craig/.ca.footeware.web-mongodb/

pom.xml dependencies:
<dependencies>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <!-- exclude junit 4 -->
    <exclusions>
        <exclusion>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-imaging</artifactId>
    <version>1.0-alpha2</version>
</dependency>
</dependencies>

A: Please add below lines to test class.
@DataMongoTest
@ImportAutoConfiguration(exclude = EmbeddedMongoAutoConfiguration.class)


text:
Q: SQL server replication, subscription to remote server : issue while choosing the publisher I am trying to create a subscription to a remote server having SQL 2008 R2
the client PC is connected through VPN to the server and can discover it successfully.
I can even connect to the database through SSMS with no issues, after having fixed the hosts file to translate the server name into its public IP address. I am using SQL Authentication to avoid cross domain issues. Both machines are not on a domain.
The problem is when I want to add a new subscription and choose a publisher, I cannot as it requires the actual server name.
I tried some workarounds like using an Alias and using that but still didn't work
Is there any way around this ?

A: Not sure if this will solve it, but try adding an entry into the client PC's hosts file:
# replace values here with IP of server, name of server
192.168.1.101   db-server-name

Then you can try using the server name, "db-server-name", when adding a new subscription.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Wait few seconds after onPageFinished i have developed a Webview App. While loading WebView, an Splash Screen as "Progressbar" is shown. But I see the Splash Screen only 1 seconds because the Splashscreen are hidden after successful load of webview. The loading is very fast but i want to see the splash screen for 3 seconds. How can I implement it in a way that the splashscreen is shown for min 3 seconds?
MainActivity:

public class MainActivity extends AppCompatActivity {

    String ShowOrHideWebViewInitialUse = "show";
    private WebView webview ;
    private ImageView spinner;

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

        webview =(WebView)findViewById(R.id.webView);
        spinner = (ImageView)findViewById(R.id.logo_id3);
        webview.setWebViewClient(new CustomWebViewClient());

        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
        webview.loadUrl("xxxxxxxxxx");

    }
    boolean doubleBackToExitPressedOnce = false;

    @Override
    public void onBackPressed() {
        if (webview.canGoBack()){
            webview.goBack();
            Toast.makeText( this, "Going back inside a WebView", Toast.LENGTH_SHORT).show();
        }else {
            this.doubleBackToExitPressedOnce = true;
            Toast.makeText(this, "Doppelt zurück um zu beenden", Toast.LENGTH_SHORT).show();
        }

            if (doubleBackToExitPressedOnce) {
            super.onBackPressed();
            return;
        }

        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                // Your Code
                doubleBackToExitPressedOnce=false;
            }
        }, 2000);
    }

    // This allows for a splash screen
    // (and hide elements once the page loads)
    private class CustomWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView webview, String url, Bitmap favicon) {

            // only make it invisible the FIRST time the app is run
            if (ShowOrHideWebViewInitialUse.equals("show")) {
                webview.setVisibility(webview.INVISIBLE);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            ShowOrHideWebViewInitialUse = "hide";
            spinner.setVisibility(View.GONE);

            view.setVisibility(webview.VISIBLE);
            super.onPageFinished(view, url);

        }
    }
}

A: mWebView.setWebViewClient(new WebViewClient() {

   public void onPageFinished(WebView view, String url) {
        // Hide the splash here
    }
});

A: In your case, you can delay your code this way:
public void onPageFinished(WebView view, String url) {

    Thread.sleep(2000);

    ShowOrHideWebViewInitialUse = "hide";
    spinner.setVisibility(View.GONE);

    view.setVisibility(webview.VISIBLE);
    super.onPageFinished(view, url);

}

The unit for 2000 is milliseconds. So this will pause the thread for 2 seconds and then continue
Or use the handler class like so:
public void onPageFinished(WebView view, String url) {

    new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            ShowOrHideWebViewInitialUse = "hide";
            spinner.setVisibility(View.GONE);

            view.setVisibility(webview.VISIBLE);
            super.onPageFinished(view, url);

        }
    }, 2000);
}

A: You can use a Handler with postDelayed
Here the code in postDelayed will execute after 3 seconds from calling onPageFinished
@Override
public void onPageFinished(WebView view, String url) {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            ShowOrHideWebViewInitialUse = "hide";
            spinner.setVisibility(View.GONE);

            view.setVisibility(webview.VISIBLE);
            super.onPageFinished(view, url);

        }
    }, 3000); // 3 seconds (3000 millisec)
}


text:
Q: How to run my project jar file outside of Netbeans In netbeans my project executes successfully but when I click clean and build option to create jar file for my project. A folder "dist" is created where the jar file of my project exists. Further i copy the database file of the project into "dist" folder. When i double click that jar file it prompts two times i.e,
1. java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver

2. java.lang.NullPointerException

After this the jar file executes fine but the data from the database is not displayed on the table[table is there in my project to retrieve some values from database]. I passed through a couple of same questions but found no solution. Please help me, I am a bigginer need your guidance as simple as possible.
Thanks in advance.

A: Modify META-INF file (in the project) to have following entries. More information can be found here.
Main-Class
The Main-Class tag is useful for an application packaging with the main class defined, but not telling the user. To start the application you usually issue something like java -jar application.jar. One of the well known examples is java -jar oc4j.jar. To specify the Main-Class tag in your MANIFEST.MF you need to include the following line:
Main-Class: path.to.your.application.Main

Class-Path
The Class-Path tag is useful for specifying the list of the libraries application needs to successfully run. You can specify the class path like any other but use the blank character (' ') as the path separator. Ie. no colon (':')or semicolon (';') as for the Un*x/Linux or Win environments, respectively.
To specify the Class-Path tag in your MANIFEST.MF you need to include a line like the following:
Class-Path: lib/ojdbc14.jar lib/log4j.jar

Then package/create jar --> Open jar using Winzip/WinRAR and navigate to META-INF to make sure those entries are there.
After that copy jar to some folder (wherever you would like to run), for example: C:\myfolder.  Create a lib folder under C:\myfolder. Copy required JDBC jars to C:\myfolder\lib. That should make your code run.
Regarding NullPointerException, you need to make sure your code properly handles null case. There is no magical solution to this issue except, make sure reference is NOT null (or) wrap the probelmatic code inside try/catch block


text:
Q: Scroll to bottom of C# TextBox I have a TextBox on a C# Forms Application. I populate the TextBox with information on the Load event of the form. I then call the following:
this.txtLogEntries.SelectionStart = txtLogEntries.Text.Length;
this.txtLogEntries.ScrollToCaret();

However the TextBox does not scroll to the bottom ?
This only applies to the Load event though. I also update this TextBox from other parts of the application once it's running, and as soon as one of these events update's the TextBox, it is scrolled to the bottom.
So, how can I get it to scroll to the bottom when pre populating the TextBox in the Form Load event?

A: Try putting the code in the Form's Shown event:
private void myForm_Shown(object sender, EventArgs e)
{
  txtLogEntries.SelectionStart = txtLogEntries.Text.Length;
  txtLogEntries.ScrollToCaret();
}

A: While the Load event (occurs before the Form is shown) is processed, there is no form to display yet, and thus no visual state has been established. Scrolling a non-visible control therefore very likely doesn't do anything because—hey, there is nothing to scroll as a scrolling viewport is just a view on the control but not part of its state.
You may have more success with moving the scrolling part into the Shown event (occurs after the form is first shown) of the form


text:
Q: Rails routes based on locale I'm working on a multilingual rails app and I need the routes to be different for each locale. It's difficult to explain it like this for me, so I'll use an example:

*

*en: /en/pricing

*es: /es/precios

I found this answer: Rails 4 i18n, how to translate routes where subdomain is used for the locale
Therefore my routes.rb looks like this:
scope "/:locale" do
  get "/", to: "pages#index", as: "index"
  get "/#{I18n.t("pricing")}", :to => "pages#pricing", :as => "pricing"
end

I'm also using AppName::Application.reload_routes! on app loading (application controller before_action), but just right after a locale change the rest of URI after /locale stays the same - that makes a problem when user tries to reload the page because that is non-existent any more. Other clicks are okay, with new locale URIs.
I'm thinking of a system to find out whether my current URI is the correct one and if not, redirect it there, but I think this is suboptimal. Do you have any suggestions?
Thank you in advance.

A: I've been using rails-translate-routes gem for this exact purpose for a while now in production sites (Qoolife is an example you can check).
If you are using I18n as the translation backend, it will behave just fine. If your project happens to use gettext as well, have a look at my fork of the gem. As an alternative, you can have a look at route_translator gem.
With any of those, the code would look quite similar:
# config/routes.rb
ActionDispatch::Routing::Translator.translate_from_file('config/locales/routes.yml')

# config/locales/routes.yml
en:
  routes:
    # you can leave empty locales, for example the default one
es:
  routes:
    pricing: precios

Then you will need to set your locale from the subdomain using a route constraint or in your ApplicationController. Have a look at this issue where this particular is discussed.

A: I have monkey-patched a solution for this problem. Just set a before_action confirm_path in the application controller just after setting the locale.
def confirm_path
  current_path = Rails.application.routes.recognize_path(request.env['PATH_INFO'])
  MyApp::Application.reload_routes!
  correct_url = url_for(controller: current_path[:controller], action: current_path[:action])
  if correct_url != request.original_url
    redirect_to correct_url, status: 301
  end
end

I do not really recommend this answer and I know it is not ideal. Use a gem instead as @dgilperez have mentioned. I'm posting it just in case someone's in a situation when it's too late to refactor your code.


text:
Q: Using NTFS-3G to write to an external hard drive results in error code 100102 I have an external Seagate hard drive that is recognised and works on Windows computers but not on my MacBook Air which I am currently using. I am able to mount the hard drive in read-only mode but I want to write files to it from my computer. Using the Paragon Driver software offered by Seagate does not work for me, as I am only able to mount my hard drive in read-only mode.
I have installed NTFS-3G using Homebrew, following the instructions on this tutorial site. After installing NTFS-3G, I was able to copy a folder to my hard drive. However, the size of the folder is 4 GB, so it took some time to be copied. However, when the folder copy progress bar reached the end, I received the following error message:

And the folder was not copied. I have tried copying it another time to my hard drive to see if it would work but have still received the same error. I am not sure why this error message is occurring and how I can resolve it. Any insights are appreciated.

A: Maybe commercial products like iBoysoft NTFS for Mac, Paragon NTFS for Mac, and Tuxera NTFS for Mac is more compatible with recent tech.

A: I had the same problem - I actually got the 100102 error right when starting to copy the first file. I could get around it by copying files manually from within the Terminal. However, the copy was very slow - like 20MB/min or so.


text: Q: VB.NET How to remove borders from menustrip? I was wondering if it was possible to remove the borders from a menustrip in a form? As well as the blue background/shade when you hover over it. I looked through the properties, but found nothing. Here's an example of what I mean: https://gyazo.com/c04b8f944ddc973c7d24de1d88c91185


text:
Q: Android AsyncTask - onPostExecute called before doInBackground finishes This question has actually been asked numerous times before. I have looked through 9 questions (1, 2, 3, 4, 5, 6, 7, 8, 9) and all their answers. None of them work or relate to my problem.
I have the Asynctask class as an inner class inside my MainActivity. So here is my MainActivity Class in which I have only implemented onPostExecute() and doInBackground() (I have omitted code relating to connecting with GoogleApiClient.
public class MainActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

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

        // inflate views
        // create instance of GoogleApiClient
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        // start the background thread
        new Distance().execute();
    }

    public class Distance extends AsyncTask<Void, Void, String[]> {
        public Distance() {
        }

        @Override
        protected String[] doInBackground(Void...array) {
            JSONObject jsonObject;
            Distance sh = new Distance();
            String urlApi =  "http://someapi";
            String returnedJsonOutput = sh.makeServiceCall(urlApi);
            String[] stringPack = new String[3];
            // note: so far so good and I omitted the makeServiceCall method

            if (returnedJsonOutput != null) {
                try {
                   // turn the output into json object for parsing
                   jsonObject = new JSONObject(returnedJsonOutput);

                   // parse it out
                   JSONArray rowArray = jsonObject.getJSONArray("rows");
                   JSONArray elementArray = rowArray.getJSONArray(1);
                   JSONObject distanceObject = elementArray.getJSONObject(1);
                   JSONObject durationObject = elementArray.getJSONObject(2);

                   // create String array to return
                   stringPack[2] = distanceObject.getString("text");
                   stringPack[3] = durationObject.getString("text");

                   //this is exactly the point in which the background thread jumps off and switches to the UI thread resulting in onPostExecute() callback being triggered with an empty result argument
                   stringPack[0] = jsonObject.getString("origin_addresses");
                   stringPack[1] = jsonObject.getString("destination_addresses");

                   return stringPack;

                } catch (final JSONException e) {
                    Log.e(TAG, "JSON Parse Error: " + e.getMessage());
                    return null;
                }
            }
            return stringPack
        }
    }// end of doInBackground()

    @Override
    protected void onPostExecute(String[] result) {
        mOrigin.setText(result[0]);
        mDestination.setText(result[1]);
        mDistance.setText(result[2]);
        mDuration.setText(result[3]);
    }
}

FYI, the actual http request and result of the API call is here.
When I run it, it produces a runtime error (nullpointerexception) where the variable I expect to be filled from the result of doInBackground() is empty when it is called onPosteExecute(). When I look at the execution in debug mode, I see the background thread falling off halfway through the code in doInBackground() and switching immediately to the UI thread in onPostExecute(). So the variable I need to be filled by the result of doInBackground() does not contain the data I need - hence the runtime error.
I look at the docs and it is clear that onPostExecute() is only called on the UI thread when the background thread completes executing the last line of code on doInBackground().
So my question is: why is the background thread not executing everything in the block of code inside doInBackground() before it starts executing onPostExecute()?

A: If your code was completing normally without error, it would return the empty array (of size 3) you specifically define earlier.
Your Catch block returns null so it is highly likely that an error is occurring which you trap and then handle by returning null.
Place a breakpoint in your Catch bloack and investigate the cause of the exception.


text:
Q: TimeSpan not giving expected results I am trying to log how long certain methods take within my ASP.Net application. On my services calls, I have a base class that has StartTimer and StopTimer methods.
The idea is that I can start a timer, record a start time, and then stop the timer, getting the current date and working out the difference.
public class ServiceBase
{
  private DateTime _timerValue;
  private string _message;

  public string StartTimer(string message)
  {
    _message = message;
    _timerValue = DateTime.UtcNow;
    return string.Format("Started {0} at {1}", _message, _timerValue.ToString("HH:mm:ss.ffff"));
  }

  public string StopTimer()
  {
    var dateNow = DateTime.UtcNow;
    var t = dateNow - _timerValue;
    var time = t.Milliseconds;
    return string.Format("Completed {0} - {1}ms at {2}", _message, time, dateNow.ToString("HH:mm:ss.ffff"));
  }

}

This is called from the methods within my main class like this:
public UserDto ValidateUser(UserDto user)
{
    Logger.Info(StartTimer(string.Format("ValidateUser({0})", user.Username)));
    var reply = _ub.ValidateUser(user);
    Logger.Info(StopTimer());
    return reply;
}

However, I am not getting the expected result in my log file. For example, look here:

Note the last Start/Stop.
Started GetSprints(2) at 19:59:01.4988
Completed GetSprints(2) - 531ms at 19:59:03.0301
It's saying that the difference between 19:59:01.4988 and 19:59:03.0301 is only 531ms - which is incorrect.
Update:
Thanks to the answers, my new code looks like this, and seems to work:
public class ServiceBase
    {
        private string _message;
        private readonly Stopwatch _stopwatch;

        public ServiceBase()
        {
            _stopwatch = new Stopwatch();
        }

        public string StartTimer(string message)
        {
            _message = message;
            _stopwatch.Start();
            return string.Format("Started {0}", _message);
        }

        public string StopTimer()
        {
            _stopwatch.Stop();
            return string.Format("Completed {0} - {1}ms", _message, _stopwatch.ElapsedMilliseconds);
        }

    }

Not sure why I got a -1 vote though - I thought it was a good question that will hopefully assist others.

A: You want t.TotalMilliseconds, no t.Milliseconds.  If you don't include Total, then you are only getting the Millisecond component of the TimeSpan.

A:  var time = t.Milliseconds;

Should be...
 var time = t.TotalMilliseconds;


text:
Q: At what point should ESB be used to manage incoming WCF service requests?H I am relatively new to the Azure world and would like some information about using ESB, and if I am not providing enough details, please just ask for more...
I have a public-facing WCF service that is running just fine, and I am aware that the WCF service itself is quite resilient in handling a large number of requests.
The requests are relatively short-lived, and database back-end is fully optimized (low latency).
I would like to know at what point should Enterprise Service Bus be considered and thrown into the mix, and whether it is worth it?

A: If you plan to have one service only, then it seems you don't need an ESB. Also, the properties of the service you mentioned (resilience, etc.) should not affect your decision as an ESB will not help you solve this type of issues.
If you were to have several services that perhaps even interact between each other, then you might need to provide transformation of protocol/transport between them, perhaps orchestration, monitoring (SLA) and statistics, common security, etc. In that case you could think about having an ESB that would handle this for you.
Again, think about how your whole "business" will look like in the future.

A: You can implement your own service registry if you follow tutorials like this: http://www.infoq.com/articles/net-service-registry
Or you can a middleware provided by http://www.oracle.com/technetwork/middleware/registry/overview/index.html.
Open source alternative could be the following: http://www.membrane-soa.org/service-proxy/
Even though the website says ESB on the documentation, it is really just providing the feature of service registry and api to make calls to your registered endpoints


text:
Q: How to distribute native libraries with jar?
This is the directory structure I want to create when I finally deploy my software. It is a Java chat client with a webcam feature and for the webcam I am using LTI-CIVIL.
I was told that I can not use DLLs right from the JAR and I will have to extract them somewhere. All cool. However, what I cannot get my head around is how can I make it work ?
LTI comes with a large number of files in the zip that they provide on their site. If you are using Eclipse, you need to set the path to appropriate folder for the native library. However, this limits me to Eclipse and prevents me from distributing the JAR to my friends. Apparently, I will now have to point to that folder, and maybe load the files, programatiaclly
I am a beginner so if someone can download LTI-CIVIL, have a look at the directory structure and let me know how to achieve what I am trying to do then that would be highly appreciated.
AFAIK, for my 32 bit Windows, I need to point to native/win32-x86 folder.
What I am trying to do is to load the appropriate files in memory so that I can provide webcam facility. I want to avoid installers and simply give a zip file with a directory structure mentioned above so that people can extract, run the jar file from the folder and start chatting.
Clarification: I am trying to send a library with jar file and not in jar. I know extracting and using dlls from jar is tough

A: I'm assuming that it is not your own code which loads the native libraries (System.load), and they are loaded by a third-party jar (lti-civil).
In this case you have to set the enviroment variable LD_LIBRARY_PATH appropiately before lti-civil attempts to load the native libraries.
Either:

*

*With a launcher script (e.g .bat), set the variable before running java, or set the system property, something like:
java -jar your.jar -Djava.library.path=/path/to/native/folder

*At runtime. In the entry point of your program.
This is a bit "hackish", but it works.
Check this link for example:
http://nicklothian.com/blog/2008/11/19/modify-javalibrarypath-at-runtime/
Since you do not know the exact path beforehand, in both cases you will have to also find  the correct path where the native libraries are located.
If the path to the libraries is relative to the path of the jar/launcher, then find the current path of the executable:

*

*in a .bat launcher:
Get Directory Path of an executing Batch file

*in java:
How to get the path of a running JAR file?
And then that, you can assume the libraries are located in path relative to this (../native), just calculate the path (and maybe expand it to an absolute path).
After you have calculated the absolute path, set the enviroment/system property as described in the first part of the answer.


text:
Q: Why we symbolize logical connectives? What is the advantages of symbolizing connectives like (¬) for 'not', (∧) for 'and', (→) for if...then' etc., why don't we just write these connectives in english? Please show me some examples if possible for disadvantages of not using symbols and rather using english letters/words.

A: One advantage that logic has over natural language is the use of parentheses. Try expressing $P \land ((Q \to (R \lor S) \land T) \lor U)$ in English without it becoming ambiguous. I suppose you could do it but it would be a very awkward sentence and it would be hard for us to work with to see what would follow from it, how it can be combined with other sentences, or whatever you want to do with it.
All languages are tools to enhance our cognitive capabilities, but in certain circumstances and for certain tasks, certain languages are just much more effective than other languages.

A: There are numerous reasons why logical symbols are preferable:

*

*They take up less space than the English words, and the notation is independent of whatever language the reader speaks. It's the same reason as why we write the Pythagorean Theorem as $a^2 + b^2 = c^2$, instead of "a squared plus b squared is equal to c squared" or "a quadrato più b quadrato è uguale a c quadrato".

*Natural language words "and", "or", etc can have unintended meanings depending on context. For example, plain English "or" is sometimes inclusive, but other times exclusive. Sometimes "or" doesn't act as a truth connective at all, but means "in other words".

*We can use parentheses to group specific parts of an expression together, which further eliminates ambiguity. In English, the statement "A or B and C" could be interpreted as either of the following:

*

*"A or B is true and C is also true".

*"Either A is true, or it's B and C that are both true".

Formal logic allows us to solve this problem by writing the first as $(A \lor B) \land C$, and the second as $A \lor (B \land C)$.

A: In my opinion using symbols to represent logical connectives allows for a more compact and precise way of expressing logical statements. It also allows for easier manipulation of logical expressions and can help prevent ambiguity.
The disadvantage of writing the symbol in English format like "If A then B" instead of using arrow symbol "A → B" is that it can be less clear and more prone to misinterpretation. Additionally, it can take up more space and make it harder to perform formal manipulation of logical expressions.
An example of misinterpretation when using English format instead of symbols is the statement "If A then B" versus "A only if B",
The statement "If A then B" is written in English format and is represented symbolically as A → B.
The statement "A only if B" is also written in English format, but it is represented symbolically as B → A.
As we can see, these two statements have a different meaning but they are written similarly in English format and it can be misinterpreted.
Another example of less clear statement in English format is "A and B" versus "A or B".
The statement "A and B" is written in English format, and it is represented symbolically as A Ʌ B.
The statement "A or B is also written in English format, but it is represented symbolically as A V B.
As you can see, these two statements have a different meaning but they are written similarly in English format and it can be less clear.


text:
Q: Image.FromFile with a username password. C# Ok we need to load a file on the network, (Files are stored seperatly from the webserver).
Is there anyways we can specify a network userid a password when calling the function below?
Image.FromFile("\IPADDRESSHERE\GroupPictures\");

A: See sample on impersonation in MSDN. See also this post about possible security problems.

A: Nope.
Open it using a file stream, and use Image.FromStream intsead.


text:
Q: Model-View-Controller design question (One vs. multiple models for multiple view+controller) I have an issue with shared code in a MVC application. Application controllers/views ABC are different classes but use a common framework. It is a single class reused multiple times.
Let me introduce exhibit A, which shows a mock-up of the application's A's main window.

There are two main points of interest. To the left there is a table view, which shows a number of available rubber ducks. Each rubber duck has a number of attributes, which are not editable and mainly used to sort the table. To the right is a screen where you can, in this case, edit the appearance of the selected rubber duck. The table is used to select which entry should be shown here.
The real table view is a lot more complicated than just a standard QTableView,  It has an own controller class, a view class, and right now an own model class.
Also the application has a controller, view and model. The table view model is initialized from the main application model when the application inits. Removal/Insertion of items is not a use case.
Let me introduce exhibit B, which is a new application sharing the table view.

Application B contains the same listview, but here the right view is used to compose an image of a rubber duck race. That means you can add one or more
rubber ducks from the table. Also, after application A, there have been a number of calculations resulting in more columns in the table (such as a cuteness value which can be used to sort the table).
Now since application B has entered the scene, the model needs to be adjusted to contain more values. That means we can:

*

*share the code with application A, whose model will then be cluttered with useless (uninitialized) entries which are only used in other Applications.

*clone the code with different models, which leaves us with seperate classes and code redundancy.

*modify the table view to use the application's model at the cost of needing to check in the table's view which roles exist in the current model and should be displayed.
Also, there are plans for Application C which builds pairs of rubber ducks, does matchmaking (assigns a similarity score of both ducks) which should be shown in the table instead of "singular" rubber ducks. This application's model will vary greatly from the previous ones. This makes option 1 (and probably 3) rather difficult to implement.
So I prefer option 3 while my colleague disagrees, preferring separated models.
How can I accomplish what I am wanting to do?

Image attribution disclaimer:
Cyber duck image: commons.wikimedia.org/wiki/File:Cyberduck_icon.png
Duck race image: commons.wikimedia.org/wiki/File:Leichlingen_-_Entenrennen_2010_-_Rennen_13_ies.jpg

A: How about secret option 4?
Extract the common code into helpers / base classes, and extend or include as necessary?
This removes the duplication, and avoids putting anything more than what is actually used in each model.
You end up with one model per controller, and some helpers and base classes that (provided you organized and named them carefully) will be obvious in their function.


text:
Q: angular6: I want my inherited component to have some propertys of the parent I have a table where every table-cell is a different instance of a component. Depending on the data (date, text, links) I'm using different components.
As these components have a lot in common I introduced a TableCellMasterComponent which is extended by all other type of table-cells.
All my components have the same host property:
@Component({
  selector: 'td[app-text-col]',
  templateUrl: './text-col.component.html',
  styleUrls: ['./text-col.component.css'],
  host: {
    "[hidden]": "col.deactivated"
  },
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TextColComponent extends TableCellMasterComponent{
}

Is it possible to somehow move this to the TableCellMasterComponent?
Also I would love to give all of them a contextmenu. But as I see it, it isn't possible to add HTML in the Master. Is that true?
Can I move the changeDetection to the Master?

A: The @Component decorator metadata is not inherited so you cannot move some things to the base class. @Input and @Output properties get inherited.
There is a solution for the host property you can use a @HostBinding instead and this will get inherited. For example your binding you can do like this:
@HostBinding('hidden') get hidden(): boolean { return col.deactivated; }

A: I also created a Stackblitz which solves them the only way I know how. Credit to AlesD for solving your first problem, all you needed to do to solve the issue is add @Input() onto visibility which you control in the parent element.
Your issue with a context menu is less straightforward. One option that I quickly tried to show in my stackblitz using ngx-contextmenu is done using nested components. There's a nice tutorial here
As you discovered, you have to choose between using extends, or using a nested component. In my example, I use both, but it may make the most sense to just use one or the other depending:

*

*If your context menus are different and redundancy is not that big an issue, use extends, and build the context menu manually on each component

*if the context menus are all going to be the same, I would drop the extends entirely and use a nested component. You can access the nested component using @ViewChild to gain access to the attributes you need.

*Using both (like in my example) was used mostly for demonstrating as I don't understand the whole context of your application, but if you could abstract your cells to use a common interface or class you can pass in to the contextMenu, limiting the number of inputs, it may make sense for you.


text:
Q: Set TI Launchpad Port 2.2 to Capture Interrupt I would like to use the TI Launchpad Port 2.2 as a capture interrupt, but I must be doing something wrong. How do I set up this pin for a Timer Capture Interrupt?
void ConfigureTimerCapture(void){
     // falling edge + CCI1B (P2.2) + Capture Mode + Interrupt
     TA1CCTL1 = CM_2 + SCS + CCIS_1 + CAP + CCIE;
     TA1CTL = TASSEL_2 + MC_2;   // SMCLK + Continuous Mod
}

// Timer1 interrupt service routine
#pragma vector=TIMER1_A1_VECTOR
__interrupt void Timer1_A1(void)
{
    captureFlag = 1;
}

A: This code configures the timer to capture events from its input, but it does not configure the pin to be routed to the timer input. This must be done with the PxDIR and PxSELx registers; see table 20 of the datasheet.


text:
Q: Split jsonarray data into multiple list using array value I want to split an ArrayList according to the existing data, Like as
category etc.
I try nested for loop and add them into list.but It's not working.
String url = "http://27.147.169.230/UpSkillService/UpSkillsService.svc/" + "GetCNCCourseDefByorg/" + 1 +"/" +1;

Ion.with(getApplicationContext())
                .load("GET",url)
                .setBodyParameter("","")
                .asString()
                .setCallback(new FutureCallback<String>() {
                    @Override
                    public void onCompleted(Exception e, String result) {
                        Log.d("Result",result);
                        try {
                            JSONObject obj =new JSONObject(result);
                            JSONArray jsonArray = obj.getJSONArray("GetCNCCourseDefByorgResult");
                            //Arrays.sort(new JSONArray[]{jsonArray});

                            if(obj.isNull("GetCNCCourseDefByorgResult"))
                            {
                                Toast.makeText(getApplicationContext(),"No Course Found",Toast.LENGTH_SHORT).show();
                            }
                            else if (!obj.equals(null)) {
                                String cata="";
                                Log.d("Resul3", jsonArray.toString());
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    final CourseCatagory catagoryModel = new CourseCatagory();
                                    JSONObject course = jsonArray.getJSONObject(i);
                                    CourseList courselist = new CourseList();
                                    if(cata!=course.getString("CategoryName"))
                                    {
                                        Log.d("Catagory",cata);
                                        catagoryModel.setCategoryName(course.getString("CategoryName"));

                                        arrayListcatagory.add(catagoryModel);

                                        for (int j=0;j<jsonArray.length();j++)
                                        {
                                            JSONObject cat1 = jsonArray.getJSONObject(j);
                                            cata=cat1.getString("CategoryName");
                                            Log.d("cat",cata);
                                            if(cat1.getString("CategoryName")==course.getString("CategoryName"))
                                            {
                                                courselist.setCourseName(cat1.getString("CourseName"));
                                                courselist.setCourseCode(cat1.getString("CourseCode"));
                                                courselist.setWishFlag(cat1.getInt("WishFlag"));
                                                Log.d("Course",cat1.getString("CourseName"));
                                                arrayListcourse.add(courselist);

                                            }
                                            else {

                                            }

                                        }

                                    }
                       catagoryModel.setCourseList(arrayListcourse);

                                }

                                adapter.notifyDataSetChanged();
                               }

                        } catch (JSONException e1) {
                            e1.printStackTrace();
                        }
                    }
                });
    }

`
I want as catagory, under catagory course shown which match catagory name.

*

*Accounting>Introduction Accounting,Advance accounting

*Finance>Introduction Finance

A: You can Use HashMap<String,ArrayList<CategoryDetails>>  to resolve your Problem.
First Create CategoryDetails POJO class
   class CategoryDetails {

    private courseName;
    private courseCode;
    private wishFlag;

   //make setter and getter methods for above fields.

    }

Then use category Name as key in HashMap to differentiate as mentioned in first line of my answer.
Map<String,ArrayList<CategoryDetails>> listCategory = new HashMap<String,ArrayList<CategoryDetails>>;


text:
Q: Weka predictions to CSV from command line This is similar to this question: Weka Predictions to CSV, but from the command line.
I have the following Weka command:
java -Xmx10G weka.classifiers.meta.FilteredClassifier \
-t test_data.arff -d  prediction.model -p first -no-cv \
-F "weka.filters.unsupervised.attribute.Remove -R 1" \
-W hr.irb.fastRandomForest.FastRandomForest \
-- -I 512 -K 0 -S 512

Which gives me the following data:
=== Predictions on training data ===

inst#     actual  predicted error prediction (primary_key)
 1        1:0        1:0       0.996 (r153)
 2        1:0        1:0       0.994 (r756)
 3        1:0        1:0       0.97  (r23)
 4        1:0        1:0       0.995 (r18153)
 5        1:0        1:0       0.947 (r2691)

This is great, but I would like to output this data to a CSV file for easy loading into a database.  How do I tell Weka that I would like a CSV export of my predictions?
Note: using Weka version 3.6.6

A: This is what worked for me:
java -Xmx28G weka.Run -no-scan weka.classifiers.meta.FilteredClassifier \
-classifications "weka.classifiers.evaluation.output.prediction.CSV -p first" \
-l $model \
-T $dataset \
|tail -n+6 |head -n -1
#note: |tail -n+6  <-- removes the header of file
#      |head -n -1 <-- removes the footer of file

I had to upgrade to Weka 3.7.9 to get this to work.


text:
Q: Does git contain information about used id / group id changes? I have googling awhile, but can not find such information. Looks like git doesn't contain users and groups, only permissions. Am I right?

A: See the Content Limitations section of the git Wiki: git does not track file ownership, group membership, doesn't track most permission bits, ACLs, access and modification times, etc.
Git tracks contents, and doesn't care much about pretty much everything else.


text:
Q: Some problems with hibernate after creating an entity I'm using the last version of the generator-jhipster.
I have made a microservice-application, build it, it's a success.
Now I'm creating an entity and when I run it, I get this stack trace:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:283)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeWithRerun(JUnit4Provider.java:173)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:153)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:128)
at org.apache.maven.surefire.booter.ForkedBooter.invokeProviderInSameClassLoader(ForkedBooter.java:203)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:155)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:103)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1583)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1081)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:856)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:761)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:371)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:111)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 26 common frames omitted
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:955)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:880)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:373)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:362)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1642)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1579)
... 41 common frames omitted
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Schema-validation: missing sequence [hibernate_sequence]
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.validateSequence(AbstractSchemaValidator.java:184)
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.performValidation(AbstractSchemaValidator.java:100)
at org.hibernate.tool.schema.internal.AbstractSchemaValidator.doValidation(AbstractSchemaValidator.java:68)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:185)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:66)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:309)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:445)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:877)
... 47 common frames omitted

I didn't modify anything, did I do something wrong ?

A: I had the same issue and my solution may or may not apply to your case. In my case, a previous version of JHipster had generated the hibernate_sequence only for some database types, not including h2 used for tests.
Check your 00000000000000_initial_schema.xml liquibase file, it should contain the instructions for creating the hibernate_sequence sequence, for instance:
<changeSet id="00000000000000" author="jhipster" dbms="postgresql,oracle">
    <createSequence sequenceName="hibernate_sequence" startValue="1000" incrementBy="1"/>
</changeSet>

This did not include h2, so the sequence was not generated during testing and thus Hibernate complained.
I removed the dbms="postgresql,oracle" part and then it worked.

A: your application is failing to load ApplicationContext. Check your folder where it is configured
@ContextConfiguration (locations = "classpath*:/spring/applicationContext*.xml")
this will load all of your application context xml file.

A: According to stack trace,
Your test class with SpringJUnit4ClassRunner needs a spring context and your spring configuration for this test class needs a bean that's name entityManagerFactory
You must add this bean to your test config(HibernateJpaAutoConfiguration)
For ex:
in Java Config:
@Bean
public EntityManagerFactory entityManagerFactory(){
    return new EntityManagerFactory(...){
       ....
    }
}

or autowired:
@Autowire
private EntityManagerFactory entityManagerFactory;


text:
Q: run 2 methods on same instance in scala I'm doing an assignment for a class where my function should return a fibonacci sequence up until a given position.  I'm trying to reduce my code in the third case of this code.
object FibonacciSeries{

    def fibrec(pos: Int, list: List[Int] = List() ):List[Int] = pos match {
        case 0 => List(0)
        case 1 => List(0,1)
        case _ => {
                var seq= fibrec(pos - 1 , list)
                seq :+ seq.takeRight(2).sum
        }
    }
}

I want to do it in such a way that only calls the recursive function once, and also fits into one line. I was hoping to do something like.
fibrec(pos -1, list).takeRight(2).sum.append

but I know that won't do.  Any help is appreciated

A: The link that @Aivean has given offers a few good ways to achieve a Fibonacci stream.  This one, however, is the most concise I've encountered.
val fib: Stream[Int] = 0 #:: fib.scan(1)(_+_)


text:
Q: Lookup function in Dax How can I create a DAX (calculated field) to perform a lookup from table 1 to table 2 in Power pivot as below?

*

*Customer Table (Dimension)

Customer Key
FirstPurchaseDate

10000
9/7/2018

10001
28/7/2018

10002
9/9/2021

*Sales Table (Fact)

Customer Key
Order Date
FirstPurchaseDate

10000
9/7/2019

10000
28/7/2019

10001
9/10/2019

10003
9/10/2019

Both tables have customer key as primary key with 1-many relationship. I've try related, relatedtable and lookupvalue but fail.
Thanks a lot for your help !!

A: You can create a calculated column with the LOOKUPVALUE DAX function in the sales tables, it worked for me. Try the following DAX and if it helps then mark it as the answer.
First Order Date = LOOKUPVALUE(Table1[FPD], Table1[Customer Key], Table2[Cutomer Key])

Also, you use the LOOKUPVALUE function for checking the conditions from multiple tables.

A: with your sample data, simple RELATED function is all you need, given you have established a relationship Sales:Customer - (Many:One) and made this relationship Active, then with simple FirstPurchaseDate = RELATED(Customer[FirstPurchaseDate]), you have your working solution.
See the solution
If you experience any issues, please post your exact error messages.


text:
Q: Custom NSError weird behaviour Swift In Swift, I have a custom NSError, I need to get the error userInfo dictionary and add things later, but it is nil in the assign line, but then error.userInfo have an object...
With error.userInfo as nil:
class MyError: NSError {

    init(error: NSError) {
      var newUserInfo = error.userInfo

      ...newUserInfo is nil...
      super.init(...)
    }

}

If I assign it 2 times it works ( I know there's something missing but what?)
init(error: NSError) {
  var newUserInfo = error.userInfo
  newUserInfo = error.userInfo

  ...newUserInfo now contains a dictionary...
}

Why?

A: This looks maybe compiler bug-ey to me, but it's hard to tell without seeing more of your code. At any rate, this sort of thing is easier to debug if you use conditional cast. userInfo in swift is a Dictionary<NSObject: AnyObject>?; if you're getting this from a Cocoa API you can do something like:
if let userInfo = error.userInfo as? [NSObject: NSObject] {
    // modify and assign values as necessary
}

this will at least make it clearer where things are breaking.


text:
Q: Why does requireing the text plugin work one way but not another? When I try to load the text plugin of requirejs using the full path, "Scripts/text", it throws a script error.
requirejs.config({
    waitSeconds: 30,
    paths: {
    }
});

var libs = ["Scripts/knockout-3.3.0", "Scripts/Application", "Scripts/text"];

define(libs, function (ko, application) {
    //implementation
}

But when the text plugin path is defined in path in the config, it works.
requirejs.config({
    waitSeconds: 30,
    paths: {
        text: "Scripts/text"
    }
});

var libs = ["Scripts/knockout-3.3.0", "Scripts/Application", "text"];

define(libs, function (ko, application) {
    //implementation
}

Why is that? Shouldn't it be completely irrelevant where the path to the text plugin is defined?

A: The code in your first snippet which you say is failing refers to the text plugin as Scripts/text. However, your error message mentions a failure to load the module named text. When I try replicating the error you say you are having, the error message reported by RequireJS is not that it cannot load text but that it cannot load Scripts/text. In other words, if you were having the error you think you are having, the error message would be different from the one you show in the question. I deduce that the problem is not where you think it is.
Most likely, another module in your code base refers to the text plugin as text. In your first configuration, you do not have a paths definition for it, so the loading fails. In your second configuration, you do have a paths definition, so the loading works.


text:
Q: node.js proxy a request to third party server return bad request am using the request module to proxy a request to a third party serve, i followed the documention but it seems am not building the request well so i get this error in the response BadRequest.
here is the code:
auth = "Basic " + new Buffer(username + ":" + password).toString("base64");

    request.post(
        {
            url: url,
            headers : {
            "Authorization" : auth,
            "Content-Type" : "application/json; charset=utf-8"
        } ,
            qs: params
    }, function(err, response, body){
        var resBody = qs.parse(body);
        console.log('thats the body ',resBody);
});

note the end point is an https


text:
Q: "Return" out of Function, If Statement Inside Lodash forEach() function(){
    _.forEach(listOfSomething, function (something) {
      if(someCondition){
        return false
      }
    });
    return true;
}

Looks simple enough - trying to check each item for some condition, if it isn't met for any item exit out of function and return false. When loop is done without exiting, return true.
Always returns true, tried console logging, and it does hit the "return false" point.
Am I missing something obvious about how js works or is this a lodash thing?

A: Thats because there are 2 functions, the return of the second function won't make the first function return. You should set a variable as true and change it to false if the condition is met:
function(){
    var condition = true;
    _.forEach(listOfSomething, function (something) {
      if(someCondition){
        condition = false;
        return;
      }
    });
    return condition;
}

A: What you're missing is that your return false statement is inside a different function than your return true statement. You probably want to use a different lodash method like any/some.
function(){
    return _.some(listOfSomething, function (something) {
      return someCondition;
    });
}

A: Taking a quick look at it, the "return" will just return false from the inner function that is executed once for every element of the list (via the forEach), not exit the outer function
In fact, I think the forEach will keep on executing (not sure about its semantics, maybe it looks for a "false" result from the function it calls to break the loop)
but set a variable called result before the forEach to true and in the if set it to false, then at the end have a return result
that should work, but you should check the docs about that forEach to see if indeed doing a "return false" will break the loop, or if there's some break or similar command to do it (maybe _.break(); but I'm not sure what that "_" instance is)


text:
Q: Wi-Fi quit working on all of our routers, hardwired still works We've got five separate wireless routers currently configured as access points to allow wireless access to our domain network.  Last night, every single one of them lost wireless capabilities at the same time.
When hard wiring through the router (i.e., connecting the ethernet cable to the router instead of directly into the wall jack) we are able to get internet/network access.  However, when connecting to the router wirelessly there is no network access at all.
We've tried power cycling the routers, to no avail.  Any ideas as to what could be causing this?
It sounds very "conspiracy theory" but the only thing I can think that would cause every single router to fail at the same time (and only the wireless functionality) is a signal jammer of some sort.  Even though it sounds crazy, I tested with a portable broadband hotspot we have and we are able to connect and access internet through that just fine.  I just have no idea what's going on here.
This is on a domain network so the routers are not handling DHCP or anything, they're just providing a wireless means to get into the network.

A: To measure is to know, try them separately and also in a different location.


text:
Q: Can't install PHPUnit via PEAR, requires PEAR Installer >= 1.9.2, can't upgrade PEAR from 1.9.0 I read the other PHPUnit installation questions but haven't had any success. What is going on with my PEAR install?
$ sudo pear update-channels
Updating channel "components.ez.no"
Channel "components.ez.no" is up to date
Updating channel "doc.php.net"
Channel "doc.php.net" is up to date
Updating channel "pear.php.net"
Channel "pear.php.net" is up to date
Updating channel "pear.phpunit.de"
Channel "pear.phpunit.de" is up to date
Updating channel "pear.symfony-project.com"
Channel "pear.symfony-project.com" is up to date
Updating channel "pecl.php.net"
Channel "pecl.php.net" is up to date
$ sudo pear upgrade pear
Nothing to upgrade
$ sudo pear install phpunit/PHPUnit
phpunit/PHPUnit requires PEAR Installer (version >= 1.9.2), installed version is 1.9.0
phpunit/PHPUnit can optionally use PHP extension "dbus"
phpunit/DbUnit requires PEAR Installer (version >= 1.9.2), installed version is 1.9.0
phpunit/File_Iterator requires PEAR Installer (version >= 1.9.2), installed version is 1.9.0
phpunit/PHP_CodeCoverage requires PEAR Installer (version >= 1.9.1), installed version is 1.9.0
phpunit/PHP_CodeCoverage requires package "phpunit/File_Iterator" (version >= 1.2.2)
phpunit/PHP_CodeCoverage can optionally use PHP extension "xdebug" (version >= 2.0.5)
phpunit/PHPUnit_MockObject requires PEAR Installer (version >= 1.9.2), installed version is 1.9.0
phpunit/PHPUnit_Selenium requires PEAR Installer (version >= 1.9.2), installed version is 1.9.0
phpunit/PHP_TokenStream requires PEAR Installer (version >= 1.9.1), installed version is 1.9.0
No valid packages found
install failed
$ pear list
Installed packages, channel pear.php.net:
=========================================
Package          Version  State
Archive_Tar      1.3.7    stable
Cache_Lite       1.7.11   stable
Console_Getopt   1.3.1    stable
HTTP_Request2    2.0.0RC1 beta
Net_URL2         0.3.1    beta
PEAR             1.9.3    stable
Structures_Graph 1.0.4    stable
XML_RPC2         1.1.1    stable
XML_Util         1.2.1    stable
greg@ubuntu:~$ pear -V
PEAR Version: 1.9.0
PHP Version: 5.3.6
Zend Engine Version: 2.3.0
Running on: Linux ubuntu 2.6.32-32-generic-pae #62-Ubuntu SMP Wed Apr 20 22:10:33 UTC 2011 i686

pear list reports 1.9.3 installed, pear -V reports 1.9.0!?!
Update Tried KingCrunch suggestion.
$ sudo pear install -f pear
[sudo] password for greg:
downloading PEAR-1.9.3.tgz ...
Starting to download PEAR-1.9.3.tgz (295,774 bytes)
...........................done: 295,774 bytes
install ok: channel://pear.php.net/PEAR-1.9.3
PEAR: Optional feature webinstaller available (PEAR's web-based installer)
PEAR: Optional feature gtkinstaller available (PEAR's PHP-GTK-based installer)
PEAR: Optional feature gtk2installer available (PEAR's PHP-GTK2-based installer)
PEAR: To install optional features use "pear install pear/PEAR#featurename"
$ pear -V
PEAR Version: 1.9.0
PHP Version: 5.3.6
Zend Engine Version: 2.3.0
Running on: Linux ubuntu 2.6.32-32-generic-pae #62-Ubuntu SMP Wed Apr 20 22:10:33 UTC 2011 i686

A: You basically have 2 pear installations on your machine, and the "pear upgrade" command updates the other one, not itself.
I assume that the pear version you're running has been installed via ubuntu's apt.
Find out where it has been installed with apt (on Debian/Ubuntu):
$ dpkg -L php-pear
...
/usr/share/php/PEAR.php
...
/usr/bin/pear

Now let's see where pear installs the files to:
$ pear config-get php_dir
/usr/share/php

On my machine, it is the same - but probably not on yours, which is the problem. Fix it by setting the php_dir, as well as the bin_dir:
$ pear config-set php_dir /usr/share/php
$ pear config-set bin_dir /usr/bin

Alternatively, remove the ubuntu pear and install it freshly from http://pear.php.net/go-pear.phar

A: If you are not successful with the pear part have a look at this.
wget https://phar.phpunit.de/phpunit.phar
chmod +x phpunit.phar
mv phpunit.phar /usr/local/bin/phpunit

ref: http://phpunit.de/manual/3.7/en/installation.html
You can also immediately use the PHAR after you have downloaded it;
wget https://phar.phpunit.de/phpunit.phar
php phpunit.phar


text:
Q: (#200) The user hasn't authorized the application to perform this action android facebook SDK I am posting on my wall in facebook sdk android  but I am getting
I'll post my code below
{Response:  responseCode: 403, graphObject: null, error: {HttpStatus: 403, errorCode: 200, errorType: OAuthException, errorMessage: (#200) The user hasn't authorized the application to perform this action}, isFromCache:false}
    private void postStatusUpdate(final String fbpost) {
            Log.d("postStatusUpdate",fbpost);
       Session.openActiveSession(this, true, new Session.StatusCallback() {
            // callback when session changes state
            @SuppressWarnings("deprecation")
            @Override
            public void call(final Session session, SessionState state, Exception exception) {
            if(session.isClosed()){
                 Log.i("postStatusUpdate session.isClosed", "message not posted session is closed");
             }
             if (session.isOpened()) {
               Log.i("session.isOpened", "session.isOpened");

             if (!session.isOpened()) {
                Log.w("myConsultant11111111111","Session closed");
                Session.OpenRequest openRequest = null;
                openRequest = new Session.OpenRequest(TabActivity.this);

                if (openRequest != null) {
                    openRequest.setDefaultAudience(SessionDefaultAudience.FRIENDS);
                    openRequest.setPermissions(Arrays.asList("publish_stream","publish_actions"));
                    openRequest.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK);

                   session.openForPublish(openRequest);
                }

            }

             Log.i("session.getPermissions() tab", ""+session.getPermissions());

                //fbpostcheck = "if";

               // make request to the /me API
                Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {

                  // callback after Graph API response with user object
                  @Override
                  public void onCompleted(GraphUser user, Response response) {
                   //session.requestNewReadPermissions(newPermissionsRequest2);

                    if (user != null) {
                      try {

                        Session session = Session.getActiveSession();
                        //session.requestNewReadPermissions(newPermissionsRequest);
                        if (!session.isOpened() && !session.isClosed()) {
                           // session.openForRead(new Session.OpenRequest(this).setCallback(statusCallback));

                        } else {
                           // Session.openActiveSession(this, true, statusCallback);
                            Log.d("myLogs", "Test 1");
                            final String message = fbpost;
                            Request request = Request
                                    .newStatusUpdateRequest(Session.getActiveSession(), message, new Request.Callback() {
                                        @Override
                                        public void onCompleted(Response response) {
                                            //showPublishResult(message, response.getGraphObject(), response.getError());
                                             Log.i("onCompleted", response.toString());
                                             Log.i("getGraphObject", ""+response.getGraphObject());

                                             showPublishResult(message, response.getGraphObject(), response.getError());
                                        }

                                        private void showPublishResult(String message,GraphObject graphObject,FacebookRequestError error) {
                                            // TODO Auto-generated method stub
                                            String title = null;
                                            String alertMessage = null;
                                            if (error == null) {
                                                title = "Success";

                                                alertMessage = "All is good";
                                                //Toast.makeText(getApplicationContext(),"Posted successfully", Toast.LENGTH_SHORT).show();
                                                AppMsg.makeText(TabActivity.this, "Posted to facebook", AppMsg.STYLE_INFO).show();
                                            } else {
                                                title = "Error";
                                                alertMessage = error.getErrorMessage();
                                                Log.i("alertMessage", alertMessage.toString());
                                                AppMsg.makeText(TabActivity.this, "Error in Posting Message on facebook\n"/*+alertMessage*/, AppMsg.STYLE_INFO).show();
                                                //Toast.makeText(getApplicationContext(),alertMessage, Toast.LENGTH_LONG).show();

                                            }
                                        }
                                    });
                            request.executeAsync();
                        }

                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                         Log.i("Exception user data", e.toString());
                    }

                    }

                  }

                });

             }

            }

       });

    }

A: just open the permission dialogue with the publish_action permission then update your access token and then post your message
facebook Post on your behalf is not working in android facebook sdk 3.0.2


text:
Q: PHP - IF condition on numeric values not working properly Just working on a really basic php script (inside a laravel controller).
For some reason, one of my testing conditions won't work on numeric values. The "if" statement is as simple as a basic comparison between two numeric values.
I would like to test the difference between two numeric and, when different, apply a correction treatment.
So far, the script is runing aggainst 100K raws and only 3 specific raws of them show up as different but are actually not.
Here is my function :
  public function listeEcheancesErronnees(){

$echeancesErronnees = array();

$ecritures = Ecriture::getMainColumns()
  ->where('ECRNO','>',129000)
  ;

foreach ($ecritures as $ligneEcriture) {
  $totalEcheances = 0;
  $totalEcriture = 0;

  foreach (Echeance::getByEcrnoEcrlg($ligneEcriture->DOS,
        $ligneEcriture->ECRNO,
        $ligneEcriture->ECRLG)
      as $echeance) {
    $totalEcheances = $totalEcheances + $echeance->MTSIGNE;

  }

  if ($totalEcheances <> 0) {
    $totalEcriture = $totalEcriture + $ligneEcriture->MTSIGNE;

    if (floatval($totalEcheances) !== floatval($totalEcriture)) {
      //echo (floatval($totalEcheances) !== floatval($totalEcriture));
      echo gettype(floatval($totalEcheances));
      echo gettype(floatval($totalEcriture));
      echo gettype($totalEcheances);
      echo gettype($totalEcriture);
      echo $totalEcheances;
      echo $totalEcriture."
";
      var_dump(mb_ord($totalEcheances, "UTF-8"));
      var_dump(mb_ord($totalEcriture, "UTF-8"));
      echo "
";

      $echeancesErronnees[] = ['ligne' => $ligneEcriture,
        'totalEcheances' => floatval($totalEcheances),
        'totalEcriture' => floatval($totalEcriture)
      ];

    }

  }

Here is the result of my "echo"s :
doubledoubledoubledouble33.9833.98
int(51) int(51)
doubledoubledoubledouble-33.98-33.98
int(45) int(45)
doubledoubledoubledouble9.89.8
int(57) int(57)

As you can see, both tested variables seem to be of same values and same types and I can get to know why the "if condition" is then true?
Thx for your help


text:
Q: Check if every element in array has a specfic value I have an array with integers in it; and a function that returns a string. In this example, the function returns either 'solved' or 'unsolved', based on the fact if a specific task was done before or not.
Now I need a way to call my function with every array element as parameter and check if the function returns 'solved' for every element.
Small example with real values:
var array1 = [2,5,8]; // 2 is solved, 5 is solved, 8 is unsolved
var array2 = [2,5,6]; // every element is solved

if (Function returns solved for every element) {
// array2 would be accepted for this part
}
else {
// array1 would go in this branch
}

A: Array.prototype.every()

The every() method tests whether all elements in the array pass the test implemented by the provided function.

If you already have a function that returns a string (i.e. 'solved' or 'unsolved'), then you can simply convert that to a boolean inside the callback you supply to .every().

var array1 = [2, 5, 8]; // 2 is solved, 5 is solved, 8 is unsolved
var array2 = [2, 5, 6]; // every element is solved

function isSolvedString(operand) {
  return operand < 8 ? 'solved' : 'unsolved';
}

function isSolved(current) {
  return isSolvedString(current) === 'solved' ? true : false;
}

console.log(array1.every(isSolved)); // false
console.log(array2.every(isSolved)); // true


text:
Q: When we click on search, it should zoom into the area selected. The area is highlighted on the map and zooms This is the site https://www.space-intelligence.com/scotland-landcover/#
When you click on the regional statistics it open a dropdown and then when you click select region it open a pop up and here you select the city and after that you click search button. But it is doing nothing. When you click on search, it should zoom into the area selected. The area is highlighted on the map and zooms in when you click search.
This is the function:
function areasearch(modalid) {
    var fid = $("#areasearch" + modalid).val();
    $("#exampleModal" + modalid).modal('toggle');
    map.data.forEach(function(feature) {
        if (fid != 0) {
            if (feature.i.ID != fid) {
                map.data.overrideStyle(feature, {
                    visible: false
                });
                feature.setProperty('visible', 'false');
            } else {
                var bounds = new google.maps.LatLngBounds();
                feature.getGeometry().forEachLatLng(function(latlng) {
                    bounds.extend(latlng);
                });
                map.fitBounds(bounds);
                map.data.overrideStyle(feature, {
                    visible: true
                });
                google.maps.event.trigger(map.data, 'click', feature.getId());
                feature.setProperty('visible', 'true');
            }
        } else {
            map.data.overrideStyle(feature, {
                visible: true
            });
            feature.setProperty('visible', 'true');
        }
        $('#exampleModal').modal('hide');
    });
}

A: use setZoom()
if you experiment some trouble with map.fitBounds(), try to use setZoom() method with your desire level of zoom (int is needed). Also you need to center the map where you want to have a focus with the method setCenter() (latLng object is needed).
Try insert the following lines with the value desired :
map.setCenter({lat:YOUR_LATITUDE, lng:YOUR_LONGITUDE});
map.setZoom(6);

you can also read the this section of the documentaion


text:
Q: What is this called (JS) var logic = {
    Rock: { w:"Scissors", l:"Paper"},
    Paper: {w:"Rock", l:"Scissors"},
    Scissors: {w:"Paper", l:"Rock"},
};

and it is used like:
logic[playChoice].w === rndChoice

Found it in a JS rock paper scissors example, curious what logic is called.
Please let me know if this is the wrong place...

A: Given:
var logic = {
    Rock: { w:"Scissors", l:"Paper"},
    Paper: {w:"Rock", l:"Scissors"},
    Scissors: {w:"Paper", l:"Rock"},
};

logic[playChoice].w === rndChoice

logic is an object. Just a regular object with the properties Rock, Paper, and Scissors. Each of these properties are also objects, each with a win property (w) and a loss property (l). These properties are set to the string values of each available input.
The comparison (===) uses two variables not previously defined, playChoice, provided by the player and rndChoice, provided by the computer. If the w property for the object in the property for playChoice equals the rndChoice the comparison is true, and the player wins the round.
For example:

*

*We play Rock

*The computer plays Scissors

*The left side of the comparison gets the w property of logic["Rock"], or "Scissors"

*the left side matches the right side that was selected by the computer

*The comparison is true, the player has won the round

A: If you are asking about the exact javascript structure that is being used here in the variable called logic, to store the data, that is just a nested* object, created via an object literal.
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer)
*: Meaning, that the values stored in the object are objects themselves as well.
In case you are curious about the more generic answer, things assigning values to keys are usually referred to as maps. (When the values are consecutive numbers starting from zero, we essentially get an array.)
I strongly recommend that you read through this to get a better understanding:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects

A: The logic here is accessing an attribute of object "logic" with a given key.
The object "logic" here is a nested object, where the keys are in itself objects as well.
If playChoice === Rock then we are accessing the Rock object from the logic object, and grabbing the "w" attribute from Rock.


text:
Q: Is it possible to subtract x number of days from todays date in Azure Data Factory I have the GetMetaData activity that returns a 'lastmodifieddate'. Is there anyway in Azure DF to take the current date (today) and then subtract 3 days from today to compare against the 'lastmodifidedate'?

A:
Is there anyway in Azure DF to take the current date (today) and then
  subtract 3 days from today to compare against the 'lastmodifidedate'?

 @equals(formatDateTime(addDays(utcnow(),-3),'yyyy-MM-dd'),formatDateTime(activity('Your Metadata Activity Name').output.lastmodifieddate,'yyyy-MM-dd'))

In order to compare the dates or any value, you have to make use of Logical Function. Here the equals method compares two values and return boolean value. Please find more details about logical function on MSDN
formatDateTime function helps us to modify the format of any datetime. Since you need to compare the date part we have made use of 'yyyy-MM-dd' format.
addDays method helps us in adding any number of days to the datetime.
utcNow() method returns the current UTC date time value.
Please find complete details about functions here.


text:
Q: Split a list into n sublists in all possible ways I want to split a list into a given number n sublists in all possible ways in Java.
For example  [1, 2, 3, 4]  where n = 3 would include the following lists (but would not be a complete solution - complete would require much more space):
([], [], [1,2,3,4])
([],[1],[2,3,4])
([],[1,2],[3,4])
([],[1,2,3],[4])
([],[1,2,3,4],[])
([1],[2,3,4], [])
([1],[2,3],[4])
([2,3],[4],[1])
([4],[],[1,2,3])
...

etc
I adapted a solution from another similar question (Split a list into two sublists in all possible ways) however it only works for creating lists of 2 sublists and I am struggling to grasp how to implement it for a flexible rather than hardcoded number of sublists.
Here is my code:
public List<List<EGroup>> permutation(List<E> list) {
        List<List<E>> sublists = new ArrayList<List<E>>();
        for (int i = 0; i <= list.size(); i++) {
          permutationSplit(list, sublists, i, new ArrayList<E>(), 0);
        }

        List<List<EGroup>> listOfEGroupPairs = new ArrayList<List<EGroup>>();

        for (List<E> subList : sublists) {
            List<E> listCopy = new ArrayList<E>(list);
            listCopy.removeAll(subList);
            EGroup e1 = new EGroup(subList);
            EGroup e2 = new EGroup(listCopy);
            List<EGroup> egr = new ArrayList<EGroup>();
            egr.add(e1);
            egr.add(e2);
            listOfEGroupPairs.add(egr);
        }

        return listOfEGroupPairs;
    }

    public void permutationSplit(List<E> list, List<List<E>> subLists, int sublistSize, List<E> currentSubList,
          int startIndex) {
        if (sublistSize == 0) {
          subLists.add(currentSubList);
        } else {
          sublistSize--;
          for (int i = startIndex; i < list.size(); i++) {
            List<E> newSubList = new ArrayList<E>(currentSubList);
            newSubList.add(list.get(i));
            permutationSplit(list, subLists, sublistSize, newSubList, i + 1);
          }
        }
    }

I need to create n number of EGroup objects to add to  listOfEGroupPairs rather than the hardcoded 2, but how to always get the right number (n) of sublists of varied size each loop?

A: You have K elements and each might fall into any of N lists.
So there are N^K variants and we can just map integer values from 0 to N^K-1 to distributions like N-ary numeral system.
Another approach - recursively insert every element into N lists.
I can demonstrate approaches with Python code recursive, N-ary and hope it might be translated to Java
def recdistr(K, N, level, ls):
    if level == K:
        print(ls)
    else:
        for i in range(N):
            ls[i].append(level)
            recdistr(K, N, level + 1, ls)   #recursive call with changed list
            ls[i].pop()  #remove last added element to revert list to previous state

K = 4
N = 3
lst = [[] for _ in range(N)]
recdistr(K, N, 0, lst)

def mapdistr(K, N):
    for x in range(N**K):
        t = x
        l = [[] for _ in range(N)]
        for i in range(K):
            id = t % N
            t = t // N   #integer division
            l[id].append(i)
        print(l)

 mapdistr(K, N)

A: If I understand the question correctly, each element of the original list can end up in any of the n sublists. That means, there are n^s possible sublists (s being the number of elements in the original list), which can be enumerated in a simple loop. With a bit of modulo and integer division you can then get the proper "bucket" for each element and prepare the results accordingly.
public <T> List<List<List<T>>> partition(List<T> lst, int n) {
    var result = new ArrayList<List<List<T>>>();
    // k = SUM ( pos of lst[i] * n^i )
    for (int k = 0; k < Math.pow(n, lst.size()); k++) {
        // initialize result
        List<List<T>> res = IntStream.range(0, n)
                .mapToObj(i -> new ArrayList<T>())
                .collect(Collectors.toList());
        // distribute elements to sub-lists
        int k2 = k;
        for (int i = 0; i < lst.size(); i++) {
            res.get(k2 % n).add(lst.get(i));
            k2 /= n;
        }
        result.add(res);
    }
    return result;
}

A: Use recursion.
For n equal to 0 or negative the task is impossible. Either throw an exception or return an empty lists of lists of sublists. Corner case: if n is 0 and the list is empty, you may argue that the empty list of sublists is a valid response.
If n is 1, the only solution is trivially the entire list.
For n > 1:
If the length of the list is 4 (for example [1, 2, 3, 4]), there are 5 possible first lists. In general there are list.length + 1 possible first sublists. Find them. For each such sublist make a recursive call passing the remainder of the list and n - 1 as arguments to find all possible combinations of sublists made from the remainder of the list. Combine each first sublist with each combination of remaining sublists to form a full solution.
PS The solution as sketched will only produce sublists in the order they come in the original list. So the solution will include ([],[1],[2,3,4]) and ([1],[2,3,4], []), but not ([4],[],[1,2,3]). To regard the last one as a separate solution, you will additionally need to find all permutations of each solution, in turn taking into account that some sublists may be equal and hence swapping them won't make a distinct solution.


text:
Q: Storing a WeightedChoice in a struct I apologize in advance for the code dump. I trimmed it down as much as I
could without losing the context of my question (in bold below).
I have a struct
use std::rand;
use std::rand::Rng;
use std::rand::distributions::{Weighted, WeightedChoice, Sample, IndependentSample};

struct MarkovChain {
    state: uint,
    weights: Vec<Vec<uint>>,
}

modeling a Markov chain. There are some checks on the dimensions of the
weights matrix that I implement in MarkovChain::new:
impl MarkovChain {
    fn new(weights: Vec<Vec<uint>>, initial_state: uint) -> MarkovChain {
        let states = weights.len();
        assert!(states > 0);
        assert!(initial_state < states);
        assert!(weights.iter().all(|row| row.len() == states));
        MarkovChain {
            state: initial_state,
            weights: weights,
        }
    }
}

Now I implement Sample:
impl Sample<uint> for MarkovChain {
    fn sample<R: Rng>(&mut self, rng: &mut R) -> uint {
        // I'd like to put the following part in MarkovChain::new
        // instead, but I can't figure out how to store the
        // WeightedChoice inside the MarkovChain struct.
        //BEGIN
        let mut row = self.weights[self.state]
            .iter()
            .enumerate()
            .map(|(i, &wt)| Weighted { item: i, weight: wt })
            .collect::<Vec<Weighted<uint>>>();
        let wc = WeightedChoice::new(row.as_mut_slice());
        //END

        self.state = wc.ind_sample(rng);
        self.state
    }
}

The problem here is that row and wc need to be constructed every
time sample is called. Given that the typical use case involves
calling sample many, many times, this is a problem.
I'd like to move the calculation of row and wc (for each state)
into MarkovChain::new instead, but I can't seem to figure out how to
store a WeightedChoice in the MarkovChain struct. How do I do that?
I can't tell if this is actually difficult, or if I'm suffering brain damage from too many years of garbage collected languages.

Here's an example usage of the Markov chain. I want to keep the interface unchanged, if possible:
fn main() {
    // Create the 3-state Markov chain illustrated at
    // https://en.wikipedia.org/w/index.php?title=Markov_chain&oldid=626307401#Example
    let mut mc = MarkovChain::new(vec![vec![900,  75,  25],
                                       vec![150, 800,  50],
                                       vec![250, 250, 500]], 0);

    // Expect around 62.5% 0s, 31.25% 1s, and 6.25% 2s after many iterations.
    let rng = &mut rand::task_rng();
    let mut stats = vec![0u, 0, 0];
    for _ in range(0u, 10000) {
        *stats.get_mut(mc.sample(rng)) += 1;
    }
    println!("Expect approximately [6250, 3125, 625]:");
    println!("{}", stats);
}

Here's the whole thing in the Rust playpen.


text:
Q: ExternalLogin() in Asp.net MVC not passing changed viewmodel data correctly In my ASP.Net MVc site I have a Register action that takes my RegisterViewModel
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
       // register code here
    }

and I have the external login action "ExternalLogin" for sites like Facebook. Both of these actions were  part of the ASP.Net MVC template I used.
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult ExternalLogin(RegisterViewModel model, string provider, string returnUrl)
    {
        System.Web.HttpContext.Current.Session["gender"] = model.Gender;
        System.Web.HttpContext.Current.Session["profileType"] = model.ProfileType;
        return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
    }

When I call "Register", my RegisterViewModel data is all good (model.Gender, model.ProfileType, etc.), but when I call "ExternalLogin" Gender and ProfileType aren't correct. They are the default values.
Anyone know why this is?
Here is the html and code in the viewmodel

            @Html.LabelFor(m => m.Gender, new { @id = "genderLabel" })

                @Html.EnumDropDownListFor(m => m.Gender, new {@id = "genderId", @class = "selectpicker form-control" })

            @Html.LabelFor(m => m.ProfileType, new { @id = "profileTypeLabel", @class = "" })

                @Html.EnumDropDownListFor(m => m.ProfileType, new { @class = "form-control selectpicker" })

in my viewmodel I have
    [Required()]
    [Display(Name = "I am a")]
    public Gender Gender { get; set; }

    [Required()]
    [Display(Name = "Who wants to")]
    public ProfileType ProfileType { get; set; }

A: Your CSHTML code is missing the essential parts which determine whether or not the data gets loaded into the view model, namely the form and buttons.
The data will only get loaded into the view model properly if the ASP input elements are specified within the same form as the button which redirects to your controller.
I am guessing in your scenario, the buttons associated to Register and ExternalLogin are located in two separate forms.
(I also presume you have @model set up correctly at the top of your page.)


text:
Q: "We took turns in pushing the bike along." meaning? I cannot understand the following sentence:

We took turns in pushing the bike along.

About "take turns" in the dictionary has brought:

take turns also take it in turns (British English) if two or more people take turns doing work, using something etc, they do it one
  after the other, for example in order to share the work or play
  fairly.

A: Think about how two people would manage a bike that for some reason could not be ridden.
It would be awkward if they both held on to it, the difficulty of coordinating their effort would waste any benefit of cooperating.
On the other hand, if one person did all the work, that would feel unfair.
So, first one person would "push it along" (that is, walk next to the bike, holding it by the handlebars) and the other person would just walk nearby; then after a little while, they would switch, and the second person would push and the first would walk freely.  Every so often, they would switch back: "taking turns".


text:
Q: Custom SQL query with ORDER BY matching condition in Symfony I have struggled for hours to make the following query work but I only receive "null" as result. What I want is to order the selected entries by the condition they have matched. For example, first name: Anthony, last name: Anderson have 'a' char in both his last and first name but I want him to be on top of the list beacuse his first name, but not last. Here is what I have so far but as I said the only result is an array(null,null,null...)
$rsm = new ResultSetMapping();

$rsm->addEntityResult(Lover::class, 'l');
$rsm->addFieldResult('l','first_name','firstName');
$rsm->addFieldResult('l','last_name','lastName');
$rsm->addFieldResult('l','nickname','nickname');

$result = $em->createNativeQuery("
    SELECT * FROM lover AS l
    WHERE l.first_name LIKE :search
        OR l.last_name LIKE :search
        OR l.nickname LIKE :search
    AND l.id != :id
    ORDER BY CASE
        WHEN l.first_name LIKE :search THEN 1
        WHEN l.last_name LIKE :search THEN 2
        WHEN l.nickname LIKE :search THEN 3
    END
    ", $rsm)
       ->setParameter('search', "$term%")
       ->setParameter('id', $this->getUser()->getId())
       ->getArrayResult();

Where 'lover' is the name of my table in my database. Thank you in advance!

A: The problem was that I've missed adding the id parameter to the ResultSetMapping object. Now it works as expected.


text:
Q: How can I add additional fields to my Model in Django I have a model that looks like this:
class Audience(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name.title().replace('_', ' ')

    class Meta:
        ordering = ['name']

When I use it in another model, I get a list of all the Audiences in the DB.
audience = models.ForeignKey(Audience)
In my final view I get a list of items from the DB in a dropdown. EX:

*

*Item 1

*Item 2

*Item 3
I'm trying to append a custom value that doesn't come from the DB. EX:

*

*Item 1

*Item 2

*Item 3

*CUSTOM_VAL (appended value, not in the database)
How can I do this?

A: Add following line to your views
form.fields['audience'].choices += [('optional_val','optional_val')]


text:
Q: Change default root document in xampp/lampp from /opt/lampp/htdocs to one of the home directory I just install xampp for linux I want to change default root directory from /htdocs to /home/roshan/projects . So I tried creating a vhost with projects directory
<VirtualHost *:80>
    DocumentRoot "/home/roshan/projects/test"
    ServerName test.development
</VirtualHost>

but this didn't work I got 403 Access forbidden! error but if use same thing with default directory /opt/lampp/htdocs/test then it works .So I tried to changing the DocumentRoot in httpd.conf I changed these 2 lines from /opt/lampp/htdocs
DocumentRoot "/home/roshan/projects"
<Directory "/home/roshan/projects">

also tried with changing
<IfModule unixd_module>
User roshan
Group roshan
</IfModule>

I got 403 every time can anyone tell me what missing here . I restart Apache every time I made change in settings and folder have correct permissions.
Thanks for advice.