text:
Q: Unable to find a user-defined type in a c++ unordered set with custom operator==() Problem Statement: Iterate over an array of objects and check if the object exists in an unordered_set.
Goal: I could have thousand of objects in one container to check their existence in millions of objects in another container. I choose unordered_set for its constant finding complexity and vector for iterating. I'm new to this and if you have any alternate approach, I'd really appreciate it.
Issue: unordered_set find isn't working as expected or I got the concept wrong!
Main:
int main() {
  std::vector<std::unique_ptr<Block>> vertices;

  vertices.push_back(std::make_unique<Block>("mod1", "work"));
  vertices.push_back(std::make_unique<Block>("mod2", "work"));
  vertices.push_back(std::make_unique<Block>("mod3", "work"));

  std::unordered_set<std::unique_ptr<Block>> undefs;

  undefs.insert(std::make_unique<Block>("mod1", "work"));
  undefs.insert(std::make_unique<Block>("mod2", "work"));

  for(auto& vertex : vertices) {
    auto search = undefs.find(vertex);
    if(search != undefs.end()){
      std::cout << "Block: " << vertex->getName() << "\n";
    }
  }
}

Block Class Overload:
bool Block::operator==(std::unique_ptr<Block>& block) const {
  return block->getName() == mName;
}

Expected Output:
mod1
mod2
Block:
#pragma once

#include <string>
#include <memory>

using std::string;

class Block {
  private:
    string mName;
    string mLib;
  public:
    Block(string const& name, string const& lib);
    string getName() const;
    string getLib() const;
    bool operator==(std::unique_ptr<Block>& block) const;
};

A: An unordered_set requires a hashing function and a comparison function. You are using the existing hashing and comparison functions for std::unique_ptr, which is definitely not what you want.
I would not suggest trying to change the behavior of std::unique_ptr<Block> because that will lead to confusion in other code that wants normal semantics for pointers. Instead, add normal hashing and comparison functions for Block and pass customized ones to the constructor of the unordered_set.

A: You are trying to compare pointers, not values.
You need to specify hashing function for class Block.
For example, if you want to use mName as key the code will be the following:
class Block {
private:
    string mName;
    string mLib;
public:
    Block(string const& name, string const& lib)
    {
        mName = name;
        mLib = lib;
    }
    string getName() const {
        return mName;
    };
    string getLib() const {
        return mLib;
    }
    bool operator==(const Block & block) const;
};

template<> struct std::hash<Block> {
    std::size_t operator()(const Block & block) const noexcept {
        return std::hash<std::string>{}(block.getName());
    }
};

bool Block::operator==(const Block & block) const {
    return block.getName() == mName;
}

int main() {
    std::vector<Block> vertices;

    vertices.emplace_back(Block("mod1", "work"));
    vertices.emplace_back(Block("mod2", "work"));
    vertices.emplace_back(Block("mod3", "work"));

    std::unordered_set<Block> undefs;
    undefs.emplace(Block("mod1", "work"));
    undefs.emplace(Block("mod2", "work"));

    for (auto& vertex : vertices) {
        auto search = undefs.find(vertex);
        if (search != undefs.end()) {
            std::cout << "Block: " << vertex.getName() << "\n";
        }
    }
}

A: The problem there is that you are trying to compare pointers, which are different!
I'dont know the reasons behind using unique_ptr<> but by doing that you are actually trying to compare identities, instead of states which is what you want.
So you can see what I mean, let's say the first Block object is at position 100 in your memory. That would be its identity. So we have object1 whose state is "mod1, work" and whose identity is 100. Then we have object2, whose identity is 150 but its state is the same as object1, "mod1, work".
All what you have both inside the vector and the unordered_set are pointers, so you have memory positions. When inserting them in the vector, you inserted, let's say, position 100. But in the unordered_set you inserted 150. They have the same state, but find method is looking for a memory position.
I hope my answer was helpful. If you find any mistakes here or think differently please let me know. Good luck! :)


text:
Q: Trouble with Django ASGI (DAPHNE) Deployment on HEROKU i've been trying to deploy for the last couple days and I just can't seem to get it working:
on heroku , it says application deployed but then when i go into the logs I see errors. I try opening up the app (for example, admin page) and I get application error. I've tried calling the get_asgi_application prior to importing anything else, that didn't work.  Here are the errors i recieve:
ERROR
   File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 136, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
 django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
Process exited with status 1
 State changed from starting to crashed

at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=myappname.herokuapp.com request_id=18f76666-adff-40f8-83ae-55df56d78208 fwd="24.150.189.187" dyno= connect= service= status=503 bytes= protocol=https

my asgi file:

import os
from django.core.asgi import get_asgi_application
import django
#from channels.auth import AuthMiddlewareStack

#from channels.security.websocket import AllowedHostsOriginValidator
from channels.routing import ProtocolTypeRouter, URLRouter

#from .settings import ALLOWED_HOSTS
from myappnameapp.routing import *

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myappname.settings')
django.setup()

#from django.urls import path

django_asgi_app = get_asgi_application()
from myappname.auth_middleware import TokenAuthMiddleware

application = ProtocolTypeRouter({
    # (http->django views is added by default)
    "http": django_asgi_app,
    'websocket': TokenAuthMiddleware(
        URLRouter(
            websocket_urlpatterns
        )
    ),
})

my procfile:
release: python manage.py migrate
web: daphne myappname.asgi:application --port $PORT --bind 0.0.0.0 -v2
worker: python manage.py runworker channel_layer -v2

SETTINGS file:
import dj_database_url
from pathlib import Path
import os

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['127.0.0.1',
                 'myappname.herokuapp.com', 'localhost']

# Application definition

INSTALLED_APPS = [
    'channels',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    # 3rd party
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'rest_framework',
    'rest_framework.authtoken',
    'dj_rest_auth',
    'dj_rest_auth.registration',
    'corsheaders',
    'fcm_django',
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.facebook',
    'allauth.socialaccount.providers.apple',
    'django_celery_results',
    'django_celery_beat',
    'storages',
    # local
    'myappnameapi',
    'accounts',
    'myappnameapp',

]
from firebase_admin import initialize_app
FIREBASE_APP = initialize_app()
....

i've tried adding. import django, and then calling django.setup() before everything. yet the same error keeps coming. any help would be appreciated
SOLVED!!
as per Iain Shelvington solution in the comments!!!

A: Try putting the line chat.routing import * after the call to get_asgi_application() you shouldn't need to call django.setup()
import os
import django
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application

django_asgi_app = get_asgi_application()

//it is important to import after calling get_asgi_application()
from chat.routing import *

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "Grouplisten.settings")

application = ProtocolTypeRouter({
  "http": django_asgi_app,
  "websocket": AuthMiddlewareStack(
    URLRouter(
        websocket_urlpatterns
    )
 ),
 })

redpajama_set_name: RedPajamaStackExchange


text:
Q: SPARK Exception thrown in awaitResult I am running SPARK locally (I am not using Mesos), and when running a join such as d3=join(d1,d2) and d5=(d3, d4) am getting the following exception "org.apache.spark.SparkException: Exception thrown in awaitResult".
Googling for it, I found the following two related links:
1) https://github.com/apache/spark/commit/947b9020b0d621bc97661a0a056297e6889936d3
2) https://github.com/apache/spark/pull/12433
which both explain why it happens but nothing about what to do to solve it.
A bit more about my running configuration:
1) I am using spark-core_2.11, spark-sql_2.11
SparkSession spark = SparkSession
                     .builder()
                     .master("local[6]").appName("DatasetForCaseNew").config("spark.executor.memory", "4g").config("spark.shuffle.blockTransferService", "nio").getOrCreate();

3) public Dataset buildDataset(){
...
// STEP A
// Join prdDS with cmpDS
Dataset<Row> prdDS_Join_cmpDS
                = res1
                  .join(res2, (res1.col("PRD_asin#100")).equalTo(res2.col("CMP_asin")), "inner");

        prdDS_Join_cmpDS.take(1);

// STEP B
// Join prdDS with cmpDS
Dataset<Row> prdDS_Join_cmpDS_Join
                = prdDS_Join_cmpDS
                  .join(res3, prdDS_Join_cmpDS.col("PRD_asin#100").equalTo(res3.col("ORD_asin")), "inner");
        prdDS_Join_cmpDS_Join.take(1);
        prdDS_Join_cmpDS_Join.show();

}

The exception (see below for the stack trace) is thrown when the computation reaches the STEP B, until STEP A is fine.
Is there anything wrong or missing?
Thanks for your help in advance.
Best Regards,
Carlo
=== STACK TRACE

Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 422.102 sec <<< FAILURE!
testBuildDataset(org.mksmart.amaretto.ml.DatasetPerHourVerOneTest)  Time elapsed: 421.994 sec  <<< ERROR!
org.apache.spark.SparkException: Exception thrown in awaitResult:
at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:194)
at org.apache.spark.sql.execution.exchange.BroadcastExchangeExec.doExecuteBroadcast(BroadcastExchangeExec.scala:102)
at org.apache.spark.sql.execution.InputAdapter.doExecuteBroadcast(WholeStageCodegenExec.scala:229)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeBroadcast$1.apply(SparkPlan.scala:125)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeBroadcast$1.apply(SparkPlan.scala:125)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133)
at org.apache.spark.sql.execution.SparkPlan.executeBroadcast(SparkPlan.scala:124)
at org.apache.spark.sql.execution.joins.BroadcastHashJoinExec.prepareBroadcast(BroadcastHashJoinExec.scala:98)
at org.apache.spark.sql.execution.joins.BroadcastHashJoinExec.codegenInner(BroadcastHashJoinExec.scala:197)
at org.apache.spark.sql.execution.joins.BroadcastHashJoinExec.doConsume(BroadcastHashJoinExec.scala:82)
at org.apache.spark.sql.execution.CodegenSupport$class.consume(WholeStageCodegenExec.scala:153)
at org.apache.spark.sql.execution.joins.SortMergeJoinExec.consume(SortMergeJoinExec.scala:35)
at org.apache.spark.sql.execution.joins.SortMergeJoinExec.doProduce(SortMergeJoinExec.scala:565)
at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:83)
at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:78)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133)
at org.apache.spark.sql.execution.CodegenSupport$class.produce(WholeStageCodegenExec.scala:78)
at org.apache.spark.sql.execution.joins.SortMergeJoinExec.produce(SortMergeJoinExec.scala:35)
at org.apache.spark.sql.execution.joins.BroadcastHashJoinExec.doProduce(BroadcastHashJoinExec.scala:77)
at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:83)
at org.apache.spark.sql.execution.CodegenSupport$$anonfun$produce$1.apply(WholeStageCodegenExec.scala:78)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133)
at org.apache.spark.sql.execution.CodegenSupport$class.produce(WholeStageCodegenExec.scala:78)
at org.apache.spark.sql.execution.joins.BroadcastHashJoinExec.produce(BroadcastHashJoinExec.scala:38)
at org.apache.spark.sql.execution.WholeStageCodegenExec.doCodeGen(WholeStageCodegenExec.scala:304)
at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:343)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:115)
at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:136)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:133)
at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:114)
at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:240)
at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:323)
at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
at org.apache.spark.sql.Dataset$$anonfun$org$apache$spark$sql$Dataset$$execute$1$1.apply(Dataset.scala:2122)
at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:57)
at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2436)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$execute$1(Dataset.scala:2121)
at org.apache.spark.sql.Dataset.org$apache$spark$sql$Dataset$$collect(Dataset.scala:2128)
at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:1862)
at org.apache.spark.sql.Dataset$$anonfun$head$1.apply(Dataset.scala:1861)
at org.apache.spark.sql.Dataset.withTypedCallback(Dataset.scala:2466)
at org.apache.spark.sql.Dataset.head(Dataset.scala:1861)
at org.apache.spark.sql.Dataset.take(Dataset.scala:2078)
at org.mksmart.amaretto.ml.DatasetPerHourVerOne.buildDataset(DatasetPerHourVerOne.java:115)
at org.mksmart.amaretto.ml.DatasetPerHourVerOneTest.testBuildDataset(DatasetPerHourVerOneTest.java:76)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: java.util.concurrent.TimeoutException: Futures timed out after [300 seconds]
at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:219)
at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:223)
at scala.concurrent.Await$$anonfun$result$1.apply(package.scala:190)
at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:53)
at scala.concurrent.Await$.result(package.scala:190)
at org.apache.spark.util.ThreadUtils$.awaitResult(ThreadUtils.scala:190)
... 85 more

A: Just to add to what Carlo said, I used the following Line of code:
sqlContext.setConf("spark.sql.autoBroadcastJoinThreshold", "-1")

A: I was running into this problem... none of the online searches lead to the right solution...
Well, adding sparkConf.set("spark.sql.autoBroadcastJoinThreshold", "-1") solves the problem...


text:
Q: Execute a java program without setting the classpath I have a program that resides in a directory that is not set in the path/classpath - and I want to execute it using the -cp option on my console. But I get the NoClassDefFoundException, regardless of what I set as -cp
- out
 `- de
  `- my
   `- package
    `- MainClass.class

I navigate into the package directory and try to execute the main class using
MyBook-Pro:out flopes$ java -cp . de.my.package.MainClass

What am I doing wrong here?

A: The classpath must contain

*

*jar files

*directories containing the roots of the package tree.

If your package is de.my.package, the root is de, and the directory containing de must be in the classpath.
So, if you're in the package directory, the classpath should be set to ../../..: the out directory is the one that should be in the classpath.
Or you should use . as the classpath, but launch your program from the out directory.


text:
Q: A small bug in recent reputation changes -- since when 25+1 = 24? I just visited Stack Overflow. Recent achievments change popup told me that I've got +24 reputation points. However, when I opened it up, it turned out, that I've got 25+1 = 26 points:

What am I missing? Is this a bug or by-design and I just don't get it?
EDIT: (copy of below comment, for clarification) If I'm not mistaken, score highlighted in the popup (24 in this case) should only indicate entires in achievements list, that were not yet noticed by me, that is -- those with non-white background (25 + 1 in this case). Correct me, if I'm wrong, but if I'm right, then there is a bug in calculation algorithm. I have two items, with recent changes, "unread" (not seen by me), which total amount of 26, while score popup informs me only about 24 points. This is the only thing, that I don't get here.

A: If something is removed, it is not reflected in the drop down, but indicator shows it. Maybe on some site a post you suggested an edit on got removed - check "show deleted posts" and you'll see it.


text:
Q: Can't print an element doing a map (REACT im trying to do a .map of an array I have, just to print the content.
I write console.log with the info I need, and it works, but when I have to print it, it dont' works.
Thanks all.
const [article, setArticle] = useState([])

useEffect(() => {
    axios.get(link).then((element) => {
        let data = element.data.map(element => element)
        let allArticles = [];
        allArticles.push(data)

        setArticle(allArticles.flat())
        }
    )

}, [])

let text = article.map( (element,i) =>{
    //console.log(i,element.feed)  --> this works
    <p>{element.feed} </p> // this not
})

return text;

A: you should add the return like this:
let text = article.map( (element,i) =>{
    //console.log(i,element.feed)  --> this works
    return <p>{element.feed} </p>
})

and if you don't want the console.log remember that you can return it directly like this:
let text = article.map( (element,i) => <p>{element.feed} </p>)


text:
Q: Find edges of parts that are created in linear pattern in abaqus using scripting I am currently working on my research project for my MSc. My project involves evaluating woven roving fabric using binary modelling technique. This means I represent the weave of the fabric as line/trusses and the resin/matrix as a simple block.
I have been writing my code in order to run several simulations, although at the moment I would like to run only one. My experience in Python is somewhat limited and so is my Abaqus experience. So far I have been able to create my geometry, assign my material, create the section and mesh all the parts. The assembly is made of matrix, warp1, warp2, weft1 and weft2. Once I have placed them in position, I define the linear pattern in order to create the laminate composite. This has been done all in python scripting and I can select the number of layers, spacing of wefts, warps and so fwd.I
My problems are the following:

*

*Since I can create x number of parts which can represent my warps and wefts, I would like to be able to select all the edges of each part and linear pattern and create a region from it, this would allow me to then create an embedded condition for the matrix. So far I have been working with findAt and getByBoundingBox however these require the name of the part to work, how can I make it that it selects dynamically, independent of how many parts there is? I have attempted using rootAssembly.allinstances.edges.getByBoundingBox(....) but with no success. I always end up with an empty array.

This is an example of how the model looks like assembled. In this case there are 5 layers of woven roving fabric.

*I must create spring connection between warp and weft points. Again since there are many parts and these can have x numbers and therefore different names, It becomes hard to ensure that the correct pair of parts is selected and that the spring is connected between each point. Again my biggest problem is to make the selection of the part dynamic.

If anyone could give me a hand with such problems I would really appreciate it!
This is a row of springs added manually. They are supposed to serve as interaction between the crossing of warp and weft not between layer:

A: Hoping to have understood your description correctly:
mdbModel = mdb.models[modelName]

*

*To select all the present edges you can just iterate through the instances in your Assembly, given that they are indeed present in the rootAssembly: allEdges = [eachEdge for eachEdge in eachInstance.edges for eachInstance in mdbModel.rootAssembly.instances.values()]. Creating sets and operating between sets along the way may simplify things.

*When you copy each instance, assign it a name that makes its coordinates easily identifiable (e.g. instanceName="Instance_1_3" for the repetition in position i=1 and j=3. Then, you can just look for mdbModel.rootAssembly.instances["Instance_1_2"] for its previous neighbor in the i direction and so on. If you want a simple spring between two points that are close, you can just iterate through the boundary nodes and do a getByBoundingSphere() on the nodes of the neighbor part.


text:
Q: jQuery jsonp not working as expected I am trying to implement jsonp with jQuery but it is not working I did see the example in jsonp with jquery
But in my case it is always making ajax call I am appending &callback=? at the end
I construct relative url like
var url="/pbs/getTraits.do"+ $('#pbstraits').serialize()+"&callback=?";

$.getJSON(url, null, function(data){
        document.getElementById("msg").innerHTML = data.message;
    });

is this the right way of doing it?
Also when I am sending query parameters along with url I have to encode which is the best way to do it.

A: jQuery looks for =? in the querystring.
Your URL doesn't have a querystring.  (it has no ?)
Instead, you should write
$.getJSON("/pbs/getTraits.do?callback=?"", $('#pbstraits').serialize(), ...);


text:
Q: Get both date and time in milliseconds I would like to create a function that will fill a struct with the current date and time, such as:
typedef struct DateAndTime
{
    int year;
    int month;
    int day;
    int hour;
    int minutes;
    int seconds;
    int msec;
}DateAndTime;

I know I can use localtime() from time.h, but the problem is that it gives me only time in seconds, and I want to get it also in milliseconds resolution. I know I might be able to use also gettimeofday() for this, but how can i combine those to get the above struct filled? Or maybe other function that gives milliseconds resolution?
How can i achieve this?
Note: My system is linux based.

A: You could simply use gettimeofday() to obtain the seconds and micro seconds, and then use the seconds to call localtime(). You then can fill your structure as you wish.
Line this
#include <sys/time.h>
#include <time.h>
#include <stdio.h>

typedef struct DateAndTime {
    int year;
    int month;
    int day;
    int hour;
    int minutes;
    int seconds;
    int msec;
} DateAndTime;

int
main(void)
{
    DateAndTime date_and_time;
    struct timeval tv;
    struct tm *tm;

    gettimeofday(&tv, NULL);

    tm = localtime(&tv.tv_sec);

    // Add 1900 to get the right year value
    // read the manual page for localtime()
    date_and_time.year = tm->tm_year + 1900;
    // Months are 0 based in struct tm
    date_and_time.month = tm->tm_mon + 1;
    date_and_time.day = tm->tm_mday;
    date_and_time.hour = tm->tm_hour;
    date_and_time.minutes = tm->tm_min;
    date_and_time.seconds = tm->tm_sec;
    date_and_time.msec = (int) (tv.tv_usec / 1000);

    fprintf(stdout, "%02d:%02d:%02d.%03d %02d-%02d-%04d\n",
        date_and_time.hour,
        date_and_time.minutes,
        date_and_time.seconds,
        date_and_time.msec,
        date_and_time.day,
        date_and_time.month,
        date_and_time.year
    );
    return 0;
}

A: You can feed localtime with the time_t object returned as a part ofstruct timeval by the gettimeofday:
int gettimeofday(struct timeval *tv, struct timezone *tz);

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};


text:
Q: Algorithm to check matching letters in an array (before, after, cross) I have an array of letter like so
var letters  =
     ["Y", "X", "A",
      "Y", "O", "H",
      "A", "O", "O"];

I've created a loop that checks if the letter before the current is the same and the letter after the current is the same.
for (var i = 0; i < letters.length; i++) {
  var currentLetter = i;
  var before = i - 1;
  var after = i + 1;

  if (letters[after] == letters[currentLetter]) {
    console.log("Array Position " + currentLetter + ": " + letters[currentLetter] + ' matches after');
  }
  if (letters[before] == letters[currentLetter]) {
    console.log("Array Position " + currentLetter + ": " + letters[currentLetter] + ' matches before');
  }

I'm having difficulty on how to right the logic to check if the letter across is the same ( obviously there is no cross since its one dimensional). But is there a pattern that i'm missing.  How would I write this without hardcoding the algorithm for each block?
Example:

letter[0] should check: letter[1], letter[3], letter[4]
  letter[1] should check letter [0], [2], [3], [5]
  etc..

A: I wrote this fiddle for you, I believe it is close enough I it's not covering all of the weird possible cases I guess but it's enough for you to work with:http://jsfiddle.net/0mja7zrr/4/
    var letters1  =
         ["Y", "X", "A",
          "Y", "O", "H",
          "A", "O", "O"];

    var letters2  =
         ["Y", "X", "A",
          "Y", "Y", "H",
          "A", "O", "Y"];

    function checkAcross(index, rowLength, letters){
        var indexInRow = index % rowLength;
        var rowNum = Math.floor(index / rowLength);
        var totalRows = Math.floor(letters.length/rowLength);
        var letterToCheck = letters[index];
        var delta = 0;
        //checking
        for(var i = 0; i < totalRows; i++){
            delta = Math.abs(rowNum - i); //delta between rows and elements
            var firstElementOfRow = rowLength * i; //get the index of first element
            if(firstElementOfRow >= index){
                if(letterToCheck != letters[firstElementOfRow + indexInRow + delta]){
                    return false;
                }
            }
            else{
                if(letterToCheck != letters[firstElementOfRow +indexInRow - delta]){
                    return false;
                }
            }
        }
    return true;
}

console.log(checkAcross(4,3,letters1));
console.log(checkAcross(4,3,letters2));


text:
Q: How to update user Password in Mikrotik Using Command? I am using a simple php script to add user in Mikrotik Hostspot.
Here is the code :
<?php
$connection = ssh2_connect('192.168.3.201', 22);
ssh2_auth_password($connection, 'root', 'vonlinux');
$stream = ssh2_exec($connection, 'ssh admin@192.168.3.202 /ip hotspot user add disabled=no name='.$MOBILE.' password='.$VAR.' profile=default');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);
?>

Now what i want ?
Actually with the above code i am able to create a new user in Mikrotik hotspot Now, if the user is already exit this code should update the password of that user.
Hope its clear, Any help would be Appreciated.
Thanks in Advance...!

A: Using the CLI its as easy as this:
ip hotspot user set User_Name password=New_Password
You should check in your code if the user exist to update the password or if it's a new user create it.
You could use /ip hotspot user print command to check if the user exists or not.


text:
Q: SQL query multiply decimal I'm trying to multiply two values.  One is a decimal and one is numeric.
Example - Total is what I want:
Number   Decimal   Total
900       1.111    999.9
800       1.25     1000
460       4.25     1955

In my Sql query, I've tried the following:
(ISNUMERIC(UpgradeEmptyNodesPercentageLimitForAllocation) * RawTotalNodes) as ExpectedEmptyNodeCountForUpgrade

However, it always returns Number.  How do the above?
Thanks...

A: Check the scale on your data types, if they are zero then SQL will remove the decimals
DECLARE @d1 DECIMAL(18,0) = 1.111
DECLARE @d2 DECIMAL(18,10) = 1.111

SELECT @d1,@d2

A: ISNUMERIC is really for evaluating strings, not number types -- and it only returns 0 or 1.  I think what you want to do is a CAST of your numeric and/or decimal values to one with more precision, and then multiply.  What is affecting the operation is the precision and scale of both factors to your operation, as-stored.
These types, by name, are actually interchangeable - but precision and scale are not.
Try casting both to a NUMERIC of some acceptabe precision and scale, and then multiplying.  Or, if you don't have a precision and scale that will always work, then cast to REAL, if that's an option.
Read more on MSDN.


text:
Q: How is Angular's *ngFor loop implemented? I wonder how does Angular's *ngFor directive actually work under the hood? I would like to know the whole process that happens when I use the directive.
For downvoters: I've seen the ng-for-of file, although there is no single usage of passed to *ngFor array's e.g. join() method that I know is invoked. Thanks for your support :)
Here is the plunker that shows the behavior: https://plnkr.co/edit/IXVxWrSOhLBgvSal6PWL?p=preview

A: Here is a high level overview. Suppose you define your template like this:
{{item}}

Then it's transformed to the following by the compiler:
<ng-template let-item [ngForOf]="items">
    {{item}}
</ng-template>

Then Angular applies ngForOf directive to the template element. Since this directive's host element is template, it injects the templateRef. It also injects the viewContainerRef that acts as an anchor element and will be used to add DOM elements alongside:
  constructor(
       private _viewContainer: ViewContainerRef,
       private _template: TemplateRef<NgForOfContext<T>>,

The directive defines ngForOf as an input and then waits until it's initialized and creates a differ:
  ngOnChanges(changes: SimpleChanges): void {
      const value = changes['ngForOf'].currentValue;
          this._differ = this._differs.find(value).create(this.ngForTrackBy);

Then on each check detection cycle it compares the values to the previous values using this differ:
  ngDoCheck(): void {
    if (this._differ) {
      const changes = this._differ.diff(this.ngForOf);
      if (changes) this._applyChanges(changes);
    }
  }

If the values changed, it applies the changes doing the the following things:
1) generates embedded view context for each item in items
context = new NgForOfContext<T>(null !, this.ngForOf, -1, -1)

2) creates embedded view with this context using the templateRef which effectively renders new value in the DOM
this._viewContainer.createEmbeddedView(
                this._template, context , currentIndex);

3) adds relevant values to context
  viewRef.context.index = i;
  viewRef.context.count = ilen;
  viewRef.context.$implicit = record.item;`

Now, your question:

although it doesn't explain why e..g join() method is invoked on array
  passed to

It's called by the function normalizeDebugBindingValue here because your application is running in the development mode:
function normalizeDebugBindingValue(value: any): string {
  try {
    // Limit the size of the value as otherwise the DOM just gets polluted.
    return value != null ? value.toString().slice(0, 30) : value;
                           ^^^^^^^^^^^^^^^
  } catch (e) {
    return '[ERROR] Exception while trying to serialize the value';
  }
}

If you enable production mode, this function will no longer be called. Check the plunker.


text:
Q: How to send a message to the bot developer(me) via a command? I want to create a command in discord.py that sends me a dm with a suggestion attached to it. Or it should post the request in my discord log channel. Unfortunatly i have absolutly no clue how to do this.

A: To send a message to a specific channel:
await bot.send_message(discord.Object(id='INSERT CHANNEL ID HERE'), 'INSERT MESSAGE CONTENT HERE')

To send a direct message to yourself:
user = await bot.get_user_info('INSERT YOUR ID HERE')
await bot.send_message(user, 'INSERT MESSAGE CONTENT HERE')


text:
Q: Sequelize - Nested include with N:M relationships I've been struggling with an issue lately I can't seem to figure out. We basically have 3 models.
User, Role, Organization. A user is assigned to an organization with a Role. He can have multiple roles for an organization. For example

They are connected through another model UserOrganization
When I'm trying to fetch them all with includes with the below
{
    model: Organization,
    required : true,
    include: [
        {
            model: Role,
            required : true
        },
    ],
}

I'm getting back some strange results. The User is fine, the organizations of the user is fine BUT within that organization the Roles that are fetched are not from that specific user. Are the Roles assigned to that organization to whatever user.

userOrganization.js
    UserOrganization.belongsTo(models.Organization, {
        foreignKey: 'organization_id',
    });
    UserOrganization.belongsTo(models.User, {
        foreignKey: 'user_id',
    });
    UserOrganization.belongsTo(models.Role, {
        foreignKey: 'role_id',
    });

user.js
    User.belongsToMany(models.Organization, {
        through: {
            model: models.UserOrganization,
            unique: false,
        },
        foreignKey: 'user_id',
        otherKey: 'organization_id',
    });
    User.belongsToMany(models.Role, {
        through: {
            model: models.UserOrganization,
            unique: false,
        },
        foreignKey: 'user_id',
        otherKey: 'role_id',
    });

organization.js
     Organization.belongsToMany(models.F5Connection, {
        through: {
            model: models.OrganizationF5Connection,
            unique: false,
        },
        foreignKey: 'organization_id',
        otherKey: 'f5_connection_id',
    });
    Organization.belongsToMany(models.Role, {
        through: {
            model: models.UserOrganization,
            unique: false,
        },
        foreignKey: 'organization_id',
        otherKey: 'role_id',
    });

role.js
     Role.belongsToMany(models.User, {
        through: {
            model: models.UserOrganization,
            unique: false,
        },
        foreignKey: 'role_id',
        otherKey: 'user_id',
    });
    Role.belongsToMany(models.Organization, {
        through: {
            model: models.UserOrganization,
            unique: false,
        },
        foreignKey: 'role_id',
        otherKey: 'organization_id',
    });

Where have I gone wrong here ? Is there a way to fetch the Users organizations with the Roles assigned only to him ? The other solution would be to fetch the User Roles and then match them against the Organizations after the results.
Thanks

A: The problem is you're storing user's role and organization on the same level in one record in UserOrganization.
Keeping it in mind you need to define the following associations:
user.js
User.hasMany(models.UserOrganization, {
        foreignKey: 'user_id'
    });

organization.js
Organization.hasMany(models.UserOrganization, {
        foreignKey: 'organization_id'
    });

role.js
Role.hasMany(models.UserOrganization, {
        foreignKey: 'role_id'
    });

and finally to get a user with his/her roles and organizations:
const user = await User.findByPk(userId,
  include: [{
    model: UserOrganization,
    required : true,
    include: [
        {
            model: Role,
            required : true
        },
        {
            model: Organization,
            required : true
        },
    ],
}]);

This is not exactly what you wished to get because here you'll get all user's role-organization pairs. You can't get user's distinct organizations and inside each one to get distinct roles of this user because of your data structure.


text:
Q: WPF ListBox selected item not changed while using DataTemplate My listbox is binded to an items source and selecteditem property is also binded. Most of my work is being done in selecteditem property. Actually I have two listboxes, for each item in first list box there are some child items in the collection. Against all the items that are selected in first listbox, their child items are supposed to be added in the second list box.
Problem is Selecting the item(by checking the checkbox) does not raise the SelectedItem property changed
XAML for my listbox controls are
 <ListBox SelectionMode="Multiple" ItemsSource="{Binding Charts,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding SelectedChart, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
          <ListBox.ItemTemplate>
                <DataTemplate>
                     <CheckBox Content="{Binding ChartName}" VerticalAlignment="Center" IsChecked="{Binding IsChartSelected, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
                 </DataTemplate>
            </ListBox.ItemTemplate>
</ListBox>

<ListBox ItemsSource="{Binding Tracks, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
            <ListBox.ItemTemplate>
                <DataTemplate >
                    <StackPanel Orientation="Horizontal">
                        <CheckBox  VerticalAlignment="Center" IsChecked="{Binding IsTrackSelected}"/>
                        <TextBlock Margin="5 0 0 0" VerticalAlignment="Center" Text="{Binding TrackName}"/>
                    </StackPanel>
                </DataTemplate>
   </ListBox.ItemTemplate>

My Chart Selection Changed property in view model is
  public ChartSourceForMultipleSelection SelectedChart
    {
        get { return _selectedChart; }
        set
        {
            _selectedChart = value;
            ChartSelectionChanged();
            NotifyPropertyChanged("SelectedChart");
        }
    }

A:
This binding doesn't make any sense:
<CheckBox IsChecked="{Binding IsTrackSelected,
  RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" />

This attempts to bind to a property IsTrackSelected on the outer ListBoxItem, but no such property exists.  It doesn't look like you need a RelativeSource here, provided IsTrackSelected is a property of the underlying data item.

Also, I'm not sure why you're a ListBox for the tracks collection; it looks like your concepts of track selection is separate from the ListBox concept of a selected item.  Why not use a simple ItemsControl instead?
As to your primary problem, the CheckBox in the item template is eating the mouse/focus events that would normally tell the ListBox to select the parent ListBoxItem when clicked.  You can manually update the selection state of a ListBoxItem whenever its inner CheckBox receives keyboard focus.
Add GotKeyboardFocus="OnChartCheckBoxGotKeyboardFocus" to the CheckBox your chart list item template, give the chart list box a name, e.g., x:Name="ChartsList", and write the handler in the code behind:
private void OnChartCheckBoxGotKeyboardFocus(
    object sender,
    KeyboardFocusChangedEventArgs e)
{
    var checkBox = sender as CheckBox;
    if (checkBox == null)
        return;

    var listBoxItem = ItemsControl.ContainerFromElement(ChartsList, checkBox)
                      as ListBoxItem;
    if (listBoxItem != null)
        listBoxItem.IsSelected = true;
}


text:
Q: Search multiple lists using rest API with HTTPRequest and problem with number of results returned Can anyone point me to an example or share some code on how to search multiple sites libraries with a single API Rest call?  For example, I have a side called Document Archive and in that archive I have two document lists called Archive1 and Archive2.  Here is the URL I am using to search:
https://example.com/TS/EDMS/_api/search/query?querytext='Tequila'&(path:https://example.com/TS/EDMS/GSSCDocs/)&rowlimit=33&trimduplicates=true

If I run this from a console application I get 33 rows every time.  But if I cut and paste this url into my web browser, I get only 2 results.  If I go right to the document library and do the same search I get the same 2 results.  So for some reason the rest calls from my console app are generating more results.  So I suspect it has to do with the Path: statement.  So two questions:

*

*How can I add more paths to this list?  If I want to add path https://example.com/TS/EDMS/Archive/ to the path can I do this, or do I need to make two separate calls?

*Why am I getting more results from my console application than when I do a site search or paste the url into my browser?

Here is the code I am using to post the string to the site:
 HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(queryString);
            endpointRequest.Method = "GET";
            endpointRequest.Accept = "application/json; odata=verbose";
            endpointRequest.UseDefaultCredentials = true;
            HttpWebResponse endpointResponse = (HttpWebResponse)endpointRequest.GetResponse();
            //var _searchResults = SearchResult2(endpointResponse);

            Stream webStream = endpointResponse.GetResponseStream();
            StreamReader responseReader = new StreamReader(webStream);
            string response = responseReader.ReadToEnd();
            JObject jobj = JObject.Parse(response);

            var docReturnResult = new List<DocumentSearchResult>();

            JValue rowCount = (JValue)jobj["d"]["query"]["PrimaryQueryResult"]["RelevantResults"]["RowCount"];
            int loopCount = rowCount.ToObject<int>();

            for (int i = 0; i <= loopCount - 1; i++)
            {...process results here}

A: Of you look at the documentation (https://docs.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference) you see that you can use AND, NOT and OR in your search query.
Another suggestion would be to use the SharePoint Search Query tool to fastly iterate: https://github.com/SharePoint/PnP-Tools/tree/master/Solutions/SharePoint.Search.QueryTool
Another option I sometimes use is to create a custom result source with the path as predifned queries.

A: Try changing the URL to
https://example.com/TS/EDMS/_api/search/query?querytext='Tequila+AND+path:https://example.com/TS/EDMS/GSSCDocs/'

Hope that helps

A: I appreciate all the responses and help.  Here is how I "fixed" my problem (all my fault):
http://<site>/_api/search/query?querystring='Tequila(path:http://<path>)'&rowlimit=33&trimduplicates=true

The problem I was having was the single quote after the querystring was in the wrong place.  I had it after the search term and tried using the ampersand (&) or +AND+ as suggested, but once I moved the single quote to the end of the querystring is when started working.  So everyone's answer was correct, it was my mistake of the single quote that was causing the problem. I hope this helps anyone else--watch the quotes!


text:
Q: Problem with yarn when trying to set a ruby on rails application with react Following this tutorial I am stepping into odd errors in the very first steps.
After running:
rails new rails-react-tutorial --webpack=react

I would then try after bundle install
rails webpacker:install:react  rails generate react:installyarn install

And I will get:
[DEPRECATION] The trollop gem has been renamed to optimist and will no longer be supported. Please switch to optimist as soon as possible.
rails aborted!
ArgumentError: Malformed version number string Yarn v0.1.1 2011 Jesper Kjeldgaard
/*/rails-react-tutorial/bin/rails:9:in `<top (required)>'
/*/rails-react-tutorial/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => webpacker:install:react => webpacker:verify_install => webpacker:check_yarn
(See full trace by running task with --trace)

After checking this issue, I have removed the yarn files in the bin paths for the gems as it's advised in the last comments versions/2.6.1/lib/ruby/gems/2.6.0/gems/yarn-0.1.1/lib/yarn.rb,  but then I get errors like:
rails webpacker:install:react
rails aborted!
LoadError: cannot load such file -- /*/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/yarn-0.1.1/lib/yarn.rb
/*/rails-react-tutorial/config/application.rb:7:in `<main>'
/*/rails-react-tutorial/Rakefile:4:in `<main>'
/*/rails-react-tutorial/bin/rails:9:in `<top (required)>'
/*/rails-react-tutorial/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'

So that will force me to install the gem again. I am using Rails 6.0.2.1-v and ruby 2.6.1p33 (2019-01-30 revision 66950) [x86_64-linux].

A: The yarn tool you need is not a gem but the Yarn package manager. I suspect you have installed the yarn gem which appears to be an old unused unrelated project.
Try on your command line:
gem uninstall yarn

Make sure you have the Yarn package manager installed. On a Mac, you can use Homebrew:
brew install yarn

Then retry the project installation commands, which should be:
rails webpacker:install:react
rails generate react:install
yarn install

A: I found this here and solved the issue:
for ver in $(rbenv whence yarn); do
  RBENV_VERSION="$ver" gem uninstall -ax yarn
  rm -f "$(rbenv prefix "$ver")/bin/yarn"
done
rbenv rehash


text:
Q: ggplot divergent lines with error bars I would like to graph lines diverge from the reference point 'a' to other points such as 'b', 'c', 'd', etc.,
Data:
df <- structure(list(value = c(1.40438297796257, 1.44036790976986,
1.37704383251482, 1.45355096018748, 1.40847559339844, 1.38860635968641,
1.43714387291229), group = c("a", "b", "c", "d", "e", "f", "g"
), low = c(1.38956448514689, 1.40198829989962, 1.33523395978584,
1.42008027933896, 1.37516232159193, 1.34823916425279, 1.397985577859
), up = c(1.41920147077825, 1.4787475196401, 1.4188537052438,
1.487021641036, 1.44178886520494, 1.42897355512002, 1.47630216796558
), sem = c(0.00757411399256711, 0.0120426947992103, 0.0137959906464809,
0.00953361452671253, 0.00945315870421568, 0.0130586010600045,
0.0124407008862053)), .Names = c("value", "group", "low", "up",
"sem"), row.names = c(NA, -7L), class = "data.frame")

Code:
library('ggplot2')
ggplot( df, aes( x = group, y = value, group = 1 ) ) +
  geom_line( size = 1 ) +
  geom_errorbar( width=.2, size = 1, aes( ymin = low, ymax = up ), colour="black") +
  geom_errorbar( width=.2, size = 1,
                 aes( ymin = value - sem, ymax = value + sem ),
                 colour="red") +
  geom_point( shape = 21, size = 4, fill="white")

Current Plot:

Expected Plot:

A: Not sure why you did group = 1 but you need the group var to separate the lines. Here I created dummy data points that are identical to the first data point, to be at the same group as each of the data points. Note that if you are planning to use transparency this will cause problems and will need some further fiddling.
df = rbind(df[rep(1,5),],df)

df$lineGroup = c(1:6,1:6)

ggplot( df, aes( x = group, y = value, group = lineGroup ) ) +
    geom_line( size = 1 ) +
    geom_errorbar( width=.2, size = 1, aes( ymin = low, ymax = up ), colour="black") +
    geom_errorbar( width=.2, size = 1,
                   aes( ymin = value - sem, ymax = value + sem ),
                   colour="red") +
    geom_point( shape = 21, size = 4, fill="white")

Transparency issue
If you do
ggplot( df, aes( x = group, y = value, group = lineGroup ) ) +
    geom_line( size = 1 ) +
    geom_errorbar( width=.2, size = 1, aes( ymin = low, ymax = up ), colour="black",alpha=.3) +
    geom_errorbar( width=.2, size = 1,
                   aes( ymin = value - sem, ymax = value + sem ),
                   colour="red",alpha =.3) +
    geom_point( shape = 21, size = 4, fill="white")

You'll see the first point is darker due to presence of multiple data points there

To get rid of that you need to control transparency through aes as well by adding a column that controls visibility.
 df$alpha = c('visible', rep('hidden',5), rep('visible',6))

ggplot( df, aes( x = group, y = value, group = lineGroup ) ) +
    geom_line( size = 1 ) +
    geom_errorbar( width=.2, size = 1, aes( ymin = low, ymax = up,alpha= alpha ), colour="black") +
    geom_errorbar( width=.2, size = 1,
                   aes( ymin = value - sem, ymax = value + sem,alpha=alpha),
                   colour="red") +
    scale_alpha_manual(name='',values  = c('visible' = 0.3,'hidden' = 0)) +

    geom_point(aes(), shape = 21, size = 4, fill="white")

A: Using the same data and method as OganM's answer above, you can solve the transparency issue by using a de-duped dataset in the geom_point. This should work:
ggplot( df, aes( x = group, y = value, group = lineGroup ) ) +
    geom_line( size = 1 ) +
    geom_errorbar( width=.2, size = 1, aes( ymin = low, ymax = up ), colour="black") +
    geom_errorbar( width=.2, size = 1,
                   aes( ymin = value - sem, ymax = value + sem ),
                   colour="red") +
    geom_point(data = df[!duplicated(subset(df,select=-lineGroup)),],
               shape = 21, size = 4, fill="white")

Data:
df<-structure(list(value = c(1.40438297796257, 1.40438297796257,
1.40438297796257, 1.40438297796257, 1.40438297796257, 1.40438297796257,
1.44036790976986, 1.37704383251482, 1.45355096018748, 1.40847559339844,
1.38860635968641, 1.43714387291229), group = c("a", "a", "a",
"a", "a", "a", "b", "c", "d", "e", "f", "g"), low = c(1.38956448514689,
1.38956448514689, 1.38956448514689, 1.38956448514689, 1.38956448514689,
1.38956448514689, 1.40198829989962, 1.33523395978584, 1.42008027933896,
1.37516232159193, 1.34823916425279, 1.397985577859), up = c(1.41920147077825,
1.41920147077825, 1.41920147077825, 1.41920147077825, 1.41920147077825,
1.41920147077825, 1.4787475196401, 1.4188537052438, 1.487021641036,
1.44178886520494, 1.42897355512002, 1.47630216796558), sem = c(0.00757411399256711,
0.00757411399256711, 0.00757411399256711, 0.00757411399256711,
0.00757411399256711, 0.00757411399256711, 0.0120426947992103,
0.0137959906464809, 0.00953361452671253, 0.00945315870421568,
0.0130586010600045, 0.0124407008862053), lineGroup = c(1L, 2L,
3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L)), .Names = c("value",
"group", "low", "up", "sem", "lineGroup"), row.names = c("1",
"1.1", "1.2", "1.3", "1.4", "11", "2", "3", "4", "5", "6", "7"
), class = "data.frame")


text:
Q: Count today's records I need to count only today's records
   public function sales()
{

    $h = Carbon::now();
    $recordstoday = Eventos::All();

    $data = [
        'category_name' => 'dashboard',
        'page_name' => 'sales',
        'has_scrollspy' => 0,
        'scrollspy_offset' => '',
    ];

    return view('dashboard',compact('recordstoday','h'))->with($data);
}

right now it counts all, but i need you to count today's records, to get today use Carbon

{{$turnoshoy->count('created_at')}}

A: You can count using whereDate
ModelName::whereDate('created_at',now())->count();

for getting current month
$carbon=Carbon::now();

    ModelName::whereBetween('created_at',[
                                           $carbon->startOfMonth()->toDateString(),
                                           $carbon->endOfMonth()->toDateString()
                                      ])->count();

A: just use Carbon::today()
$recordstoday = Eventos::whereDate('created_at', Carbon::today())->get();


text:
Q: table view cell selected state changes when goes to another viewcontroller? i have a custom UITableView Cell, i have selected a particular cell and goes to another ViewController, when i came back to first view controller, selected state of the cell is not visible. how will i unchanged the selected state of a cell after navigating from another viewControllers?
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   return [timeSet count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   timeSettingCell *newCell = nil;
   newCell = [tableView dequeueReusableCellWithIdentifier:identifier];
   if(newCell == nil)
   {
    NSLog(@"newCell ===================");
    NSArray *nibViews = [[NSBundle mainBundle] loadNibNamed:@"timeSettingCell"   owner:self options:nil];
    newCell  = [ nibViews lastObject];
    }
    newCell.timeLabel.text=[timeSet objectAtIndex:indexPath.row];

    if (newCell.selected==YES) {
      newCell.highlighted=YES;
      newCell.timeImage.image=[UIImage imageNamed:@"radioSelected.png"];
    }
    else {
      newCell.highlighted=NO;
      newCell.timeImage.image=[UIImage imageNamed:@"radioNotSelected.png"];
    }
return newCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
value=[[time1 objectAtIndex:indexPath.row]integerValue];

SettingsViewController *settings=[[SettingsViewController alloc]initWithNibName:nil bundle:nil andCounterValue:value];
[[self presentingViewController] dismissModalViewControllerAnimated:YES];
index=indexPath.row;
[settings release];
}
-(void)viewWillAppear:(BOOL)animated{
}

thank you

A: put like this, it'll work fine...
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

[tableView deselectRowAtIndexPath:indexPath animated:YES];

A: I think you should memorize your cell state (selected or not) using a NSArray created as a singleton, ivar or NSUserDefault and then read its state in cellForRowAtIndexPath.
EDIT: Sample code
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Do what you want

// This save the index of your selected cell on disk
[[NSUserDefaults standardUserDefaults] setInteger:indexPath.row forKey:@"selectedCell"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Create your cell

// Here you check if the cell should be selected or not
if (indexPath.row == [[NSUserDefaults standardUserDefaults] integerForKey:@"selectedCell"]) {
    newCell.highlighted=YES;
    newCell.timeImage.image=[UIImage imageNamed:@"radioSelected.png"];
} else {
    newCell.highlighted=NO;
    newCell.timeImage.image=[UIImage imageNamed:@"radioNotSelected.png"];
}

return aCell;
}

NSUserDefaults is useful to save data on your device and retrieve them later. This mean you can check your cell status even after closing and reopening your app.
To use NSUserDefaults you need to add a Settings.bundle to you project. Take a look at NSUserDefaults Class Reference


text:
Q: Using Youtube Javascript API for multiple videos I am trying to find a way to use Youtube API to have multiple videos with each in its own hidden div where each one is called up by their corresponding thumbnails. I am having a hard time finding out how to get the close button of the once hidden div to also stop that particular video. I can only get one to do it right and the other will not. My code below:

// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "//www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
  player1 = new YT.Player('popupVid1', {
    height: '408',
    width: '725',
    videoId: '6Bp1c3-AeXQ',
    playerVars: {
      wmode: "opaque"
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });

  player2 = new YT.Player('popupVid2', {
    height: '408',
    width: '725',
    videoId: '6Bp1c3-AeXQ',
    playerVars: {
      wmode: "opaque"
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });
}

// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
  event.target.playVideo();
}

// 5. The API calls this function when the player's state changes.
//    The function indicates that when playing a video (state=1),
//    the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
  if (event.data == YT.PlayerState.PLAYING && !done) {
    setTimeout(stopVideo,loop);
    done = true;
  }
}

function stopVideo1() {
  player1.stopVideo();
}

function stopVideo2() {
  player2.stopVideo();
}


text:
Q: Consistently Getting Error: $injector:nomod Module Unavailable When I Load My App I think it has something to do with the way my files are ordered but I can't figure out which ones are causing the problem.

angular.module('app')
.controller('langCtrl', function($scope, languageService){
  $scope.submit = function(model) {
    console.log(model);
    languageService.analyzeDocument(model)
  }
});
<html lang="en" ng-app="app" class="no-js"> <!--<![endif]-->
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>WIT</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="images/computer.ico"/>
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

  <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="app.css">
</head>
<body ng-controller="langCtrl">
  <div class="header">
    RecommendHER
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
  <script src="app.js"></script>
  <script src="languageService.js"></script>
  <script src="langCtrl.js"></script>
</body>
</html>

I put the index.html file and my controller in the snippet. I also have a service on the save level as app.js and the controller file. Here is the code:
angular.module('app')
.service('languageService', function($resource) {
  var apiUrl = 'http://xxx.compute-1.amazonaws.com';

 var languageResource = $resource(apiUrl + {}, {
 analyzeDocument: {
   method: 'POST',
   url: apiUrl + '/analyze_document?file=:text'
 },
 analyzeWord: {
  method: 'POST',
  url: apiUrl + '/recommend?word=":word"'
}
 });

  return {
    analyzeDocument: function(data) {
       return languageResource.analyzeDocument({data:text}).$promise;
     },
      analyzeWord: function(data) {
       return languageResource.analyzeWord({data:word}).$promise;
     }
   };
 });

Here is my app.js file:
angular.module('app', [

]);

A: You need to add empty dependencies to your module,
angular.module('app',[])

EDIT
Change the order in index.html to make your module load first,
<script src="app.js"></script>
<script src="languageService.js"></script>
<script src="langCtrl.js"></script>

A: Have you defined the 'app' module with two parameters yet:
angular.module('app', []).run(function() {});

The one parameter version expects app to already exist in order for things to be included as part of the module.
Also, ensure that the app.js file is loaded first.


text:
Q: "Pyramidizing" an array/list (in Ruby, but general solutions could probably be implemented) I'm not sure what the best word to use here.  By "pyramidizing", I mean:
[1,2,3,4].pyramidize  # => [1,1,1,1,2,2,2,3,3,4]
["a","b","c","d"].pyramidize  # => ["a","a","a","a","b","b","b","c","c","d"]

To represent visually, it could be thought of as:
[ 1,1,1,1,
   2,2,2,
    3,3,
     4    ]

Is there a way to do this that maximizes elegance?  A most ruby-like way?
I came across the "need" to do this in a project of mine.  After thinking about it, I gave up and decided to work around the problem in an ugly way.  I was wondering if there was a pretty way to do this.  So far, to do it directly, I've ended up making a separate array for each index and stretching out each array the appropriate length and combining them together.  But I don't know how to do this so it looks pretty; my solution is pretty ugly.
Added code golf tag because any solution in one line would probably make my day, but it doesn't have to be.
It doesn't really matter if your solution makes the first index the "base" of the pyramid, or the last index, because I could just reverse the array before running it.

A: irb(main):001:0> [2,1,3,5].flat_map.with_index{|i,j|[i]*(j+1)}
=> [2, 1, 1, 3, 3, 3, 5, 5, 5, 5]
irb(main):002:0> [1,2,3,4].flat_map{|i|[i]*i}
=> [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

A: Requires the new iterator fanciness in Ruby 1.9.
class Array
  def pyramidize
    reverse.map.with_index do |object, index|
      [object] * (index + 1)
    end.flatten.reverse
  end
end

[1,2,3,4].pyramidize
 => [1, 1, 1, 1, 2, 2, 2, 3, 3, 4]
["a","b","c","d"].pyramidize
 => ["a", "a", "a", "a", "b", "b", "b", "c", "c", "d"]

A: I'm not sure if you want to use the value of the list or the index to determine how much the list should repeat, but a simple solution in python that can probably transfer to ruby easily:
>>> import operator
>>> input = range(6)
>>> reduce(operator.add, [[i]*idx for idx, i in enumerate(input)])
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]

Update
Oh and to invert the counts:
>>> import operator
>>> input = range(1, 6)
>>> reduce(operator.add, [[i]*(max(input) - idx) for idx, i in enumerate(input)])
[1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5]

And of course you reversed the list in one of your examples:
>>> import operator
>>> input = range(1, 6)
>>> reduce(operator.add, [[i]*(max(input) - idx) for idx, i in enumerate(input)])[::-1]
[     5,
     4, 4,
   3, 3, 3,
  2, 2, 2, 2,
 1, 1, 1, 1, 1]

A: FWIW, this is a mathy way of doing it:
>>> A = [1, 2, 3, 4]
>>> [ A[int((sqrt(8*k+1)-1) / 2)] for k in range(len(A)*(len(A)+1) / 2) ]
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4]

Admittedly, the use of sqrt is pretty ugly.

A: Here is another way to do it in Python
>>> A=[1,2,3,4]
>>> [y for i,x in enumerate(A) for y in [x]*(len(A)-i)]
[1, 1, 1, 1, 2, 2, 2, 3, 3, 4]

But it's nicer not to create all those temporary lists
>>> from itertools import repeat
>>> [y for i,x in enumerate(A) for y in repeat(x, len(A)-i)]
[1, 1, 1, 1, 2, 2, 2, 3, 3, 4]


text:
Q: How to reset folder permissions to their default in Ubuntu? I recently typed the command
sudo chmod 777 -R /

after that some things like
sudo -i

are not working normally. So I am wondering if there is any way I could reset the folder permissions to their original state?

A: After recover sudo or selecting recover mode at the boot
It's possible to recover a whole system using debsums that verifiy file integrity and permissions.
from the man page:

apt-get install --reinstall $(dpkg -S $(debsums -c) | cut -d : -f 1 | sort -u)

Reinstalls packages with changed files

or limited to a specific path eg: /usr:
apt-get install --reinstall $(dpkg -S $(debsums -c | grep -e ^/usr ) | cut -d : -f 1 | sort -u)

or limited to a multiple set of path eg: /sbin /etc /var
apt-get install --reinstall $(dpkg -S $(debsums -c | grep -e ^/etc -e ^/sbin -e ^/var  ) | cut -d : -f 1 | sort -u)

A: It is possible to come back from this messy situation.
I ran again the same kind on issue (some bug in a script I was writing) and solved it, but you need to ask some expert's help.  Be very cautious!
First, my situation was easier to solve because I had a dual boot system (Ubuntu and my old Fedora install), but running the OS from a CD/DVD, or an USB key should do the same thing.
MPOINT=/mount/ubuntu

First I mounted my file systems like this (don't forget to create the mount points):
mount /dev/ubuntu/root $MPOINT
mount /dev/ubuntu/home $MPOINT/home

Then I ran the following command (my issue was only in a few - critical - directories) to copy the permissions on from the running system to the messy one (in fact, in my case, I installed an Ubuntu system in Virtual Box under fedora and got the permissions there):
find /etc /usr /bin /sbin -exec stat --format "chmod %a \"${MPOINT}%n\"" {} \; > /tmp/restoreperms.sh

And then I ran the restoreperms.sh script.
I was able again to boot on Ubuntu.
The content of restoreperms.sh will be something like:
(...)
chmod 755 /mount/ubuntu//etc/ppp
chmod 755 /mount/ubuntu//etc/ppp/ipv6-up
chmod 2750 /mount/ubuntu//etc/ppp/peers
chmod 640 /mount/ubuntu//etc/ppp/peers/provider
chmod 755 /mount/ubuntu//etc/ppp/ipv6-up.d
chmod 777 /mount/ubuntu//etc/ppp/resolv.conf
(...)

I didn't test it but it must work for owners and owner groups too.  Something like:
find /etc /usr /bin -exec stat --format 'chown %U:%G ${MPOINT}%n' {} \; > /tmp/restoreperms.sh^

(...)
chown root:root /mount/ubuntu//etc/obex-data-server/imaging_capabilities.xml
chown root:root /mount/ubuntu//etc/obex-data-server/capability.xml
chown root:dip /mount/ubuntu//etc/ppp
chown root:root /mount/ubuntu//etc/ppp/ipv6-up
chown root:dip /mount/ubuntu//etc/ppp/peers
chown root:dip /mount/ubuntu//etc/ppp/peers/provider
chown root:root /mount/ubuntu//etc/ppp/ipv6-up.d
chown root:root /mount/ubuntu//etc/ppp/resolv.conf
(...)

Of course, you have to take care here, that the UID and GID are the same on both systems, but for the system related users and groups, this shouldn't be an issue.
Edit:
Also, setting owner will nullify SGID and SUID flags, which causes weird problems (For example, you won't be able to perform sudo unless the permission is 4755). You must, and should only set permissions AFTER setting owners.
DO SAVE complete file permission information along with owner information.
Rk:

*

*An important thing for this is to keep an install disk synchronized with the version you are using, or at least work with the current ubuntu version.

*Now, I have this commands in a cronjob, running every day (could be weeks) in order to keep that information.  It will make the solution easier next time but, of course, as I have this now, it will never happen again. ;-)  Something like this:
0 12 * * *      /usr/bin/find / -exec /usr/bin/stat --format="/bin/chmod %a %n" {} \; |/bin/bzip2 -c > /tmp/restore_chmod.$(/bin/date +%w).sh.bz2
0 13 * * *      /usr/bin/find / -exec /usr/bin/stat --format="/bin/chown %U:%G %n" {} \; |/bin/bzip2 -c > /tmp/restore_chown.$(/bin/date +%w).sh.bz2
The right (combined) command is more something like:
`/usr/bin/find / -exec /usr/bin/stat --format="[ ! -L {} ] && /bin/chmod %a %n" {} \; -exec /usr/bin/stat --format="/bin/chown -h %U:%G %n" {} \; |/bin/bzip2 -c > /tmp/restore_fileperms.$(/bin/date +%w).sh.bz2`

Note that additional care may be required to account for parentheses in filenames (under locales, for instance) and that chown may silently unset setuid and setgid bits set by chmod. In the latter case, which would break, say, /bin/su and /usr/bin/sudo, you may need to swap the order of exec clauses above.

A: You can't undo a chmod operation; at least not in the sense of rolling back to a previous setting, which is what this situation calls for.  Arguably, you can undo a chmod operation, by chmoding each file and directory back to its original mode –– but they're not all the same; determining the original modes is tricky (as discussed in the other answers).

A: Always watch what you run as sudo.
This thread explains that you can manually set some permissions back, and a script there helps with this, but still it's a big job. Rather follow the tips in the tread to save your installed packages (markings) and reinstall the OS, and apply your saved packages markings to get your applications back.

A: Wow, you killed it. It's dead! Try logging in and using the machine as root (since you enabled it), then change the group membership of root to users. This may or may not work because I've never tried it before but its worth a shot.

A: As far as I know, only System V packages and RPMs offer a command to repair file permissions. On System V (Solaris) it is pkgchk, with RPMs it is rpm --setperms.
Unfortunately, no such command seems to exist for Debian / Ubuntu packages - but I might be wrong here.
But even with the help of these commands, it's not a trivial task to bring your system back to a sane state, and by repairing it, you can easily cause new harm to your system - if you're not careful.
Other than Joseph said, you're not the first one, and you will not be the last one to enter such a command. But the idea alone, to change file permissions to 777 on a Unix system, is a strong indication that you're not very experienced with this kind of system. The best you can do in this situation is to backup what you will need again (home directories, configuration files, mail files?), and try a fresh install.
And you should be very, very careful, when you restore your - damaged - backup files.
Good luck!
P.S.: I'm just wondering what kind of problem you wanted to solve?


text:
Q: Help identifying source of odd requests showing up in server logs Anyone seen these before? Not sure if this is related to Google Analytics or UserFly running on our site or indicative of automated attacks from user machines.
The requests come from users with all user-agent strings, and from users who make legitimate requests and from trusted users. I've matched the string in a mod_rewrite rule to return "forbidden" but I would like to know where these are coming from. They come in waves, nothing for a week or more, than many many requests in one day.
The requests are for many random pages on the site and then have this odd query string appended, which varies but always looks something like:
"GET /&data=%7C%23ujnftubnq%23%3B2392714553497-%23fwfout%23%3B%5C%5E-%23efubjmt%23%3B%5C%5E-%23ujnft%23%3B%5C%5E~ HTTP/1.1"

A: This is (at this point) somewhat of an educated speculation (er, Scientific Wild @SS Guess), but here goes:
Something's looking for or targeting PDF's
Here is the URL Decoded query string from your example above:
/&data=|#ujnftubnq#;2392714553497-#fwfout#;\^-#efubjmt#;\^-#ujnft#;\^~

Googling around for "fwfout", "efubjmt" or "ujnft" the only results that came back were PDF's.
It's hard to say if that "something" is malicious or not without knowing more about your environment.  It could be something trying to search within PDF conent on your site.  It could be something trying to find something to exploit, given the recent Acrobat vulnerabilities.
I also agree about pipe suspicion, that character always makes me twitch unless I type it in myself.

A: What kind of things do you have on your server ?
for #ujnftubnq# #efubjmt# google returned me some chinese things about resource reservation on some routers. No idea if it's relevant or not :> Just a notice.

A: This sounds a bit like it could be a botnet attempting to contact you for command & control, especially with the waves.  Either that or infection attempts from a botnet.  If you know one of the clients well enough, it'd be nice to try to gather more info from one of the sources of the URL.  Packet dumps to see if it's contacting other sites, plus just a check to see what process is doing the contacting.


text:
Q: Cannot get/set IFormFile object from  tag of View I have an upload mechanism which looks like that in the View:

        <input type="hidden" id="ProjectId" name="ProjectId" value="@Model.ProjectId"/>
        <input type="hidden" id="Name" name="Name" value= "" />
        <input type="hidden" id="Id" name="Id" value="" />

                <input type="file" asp-for="InputFile"  value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
                <input type="submit" value="Upload" id="UploadInputFileButton" onclick="UploadInstallIntructions();"/>

This is my uploadinstructions() method, which gets called when the user pushes the 'Upload'button.
script>
    function UploadInstallIntructions() {
        var name = document.getElementById('SoftwareVersionName').value;
        var id = document.getElementById("Id").value;
        var iFormFile = document.getElementById("ChooseInputFile").files[0];
        $.ajax({
            type: "POST",
            url: '@Url.Action("UploadInputFile", "SoftwareVersion")',
            data: { projectId: @Model.ProjectId, Name: name, Id: id, inputFile: iFormFile},
            cache: false,
            success: function (response) {
                window.location.href = response;
            }
        });
        return data;
    }
</script>

So this is a simple ajax call that calls a method on my controller with the specified arguments. My problem is that the last argument which should be the file data, of IFormFile type, so that I can work with it in my controller, doesn't get set. Is there a better way I can bind my IFormFile object in my view? Normally just the line :
input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>

should have worked to bind the IFormFile.
Edit: Not a duplicate of how to append whole set of model to formdata and obtain it in MVC, because my question was not about binding with FormData, but IFormFile not automattically getting created from the View.

A: Try below code:
    <form name="UpdateInstall" id="UpdateInstall" method="post" enctype="multipart/form-data">
        <input type="hidden" id="ProjectId" name="ProjectId" value="@Model.ProjectId"/>
        <input type="hidden" id="Name" name="Name" value= "" />
        <input type="hidden" id="Id" name="Id" value="" />

                <input type="file" asp-for="InputFile"  value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
                <input type="submit" value="Upload" id="UploadInputFileButton" onclick="UploadInstallIntructions();"/>

    </form>

A: Once i have done upload a image file like this..

$('input[type="file"]').ajaxfileupload({
    'action': 'uploadFile.jsp',
    'cache': false,
    'onComplete': function(response) {
        $('#upload').hide();
        BootstrapDialog.show({
            title: 'Alert!',
            message: 'Image Upload Successfully',
            buttons: [{
                label: 'Ok',
                action: function(dialog) {
                    dialog.close();
                }
            }]
        });

        var img_src = "../profilepic/" + response;
        setTimeout(5000);
        $("#image").attr("src", img_src);
    },
    'onStart': function() {
        $('#upload').show();
    }
});
<input type="file" name="datafile" accept="image/*"/>

Uploading..

If you wish to upload files like this, visit this link for
jQuery.AjaxFileUpload.js


text:
Q: How to find the first message between 2 parties in SQL? I have a messages table that looks something like this:
|   id  | sender_id |  recipient_id |
|-------------------|---------------| ...
|   1   |    23     |       20      |
|   2   |    11     |       5       | ...
|   3   |    20     |       23      |
|   4   |    23     |       20      | ...
|   5   |    7      |       11      |

I'm hoping to find the first message between any two user IDs (the IDs in the sender_id and recipient_id columns). So the result for the above sample would be:
|   id  | sender_id |  recipient_id |
|-------------------|---------------| ...
|   1   |    23     |       20      |
|   2   |    11     |       5       | ...
|   5   |    7      |       11      |

At first I thought I could group by a checksum of sender_id and recipient_id, and then take the min message ID (id), but because checksum is different depending upon order of the inputs, that returns both the first message (the intro) and the first reply. Is there an alternative to checksum in which order of inputs is irrelevant?
Or maybe there's a better way to arrive at a solution.
Any help is much appreciated.

A: You can use ROW_NUMBER:
ONLINE DEMO
WITH CTE AS(
    SELECT *,
        ROW_NUMBER() OVER(
            PARTITION BY
                CASE WHEN sender_id < recipient_id THEN sender_id ELSE recipient_id END,
                CASE WHEN sender_id > recipient_id THEN sender_id ELSE recipient_id END
            ORDER BY id
        ) AS rn
    FROM messages
)
SELECT
    id, sender_id, recipient_id
FROM CTE
WHERE rn = 1
ORDER BY id

You need partition by the smaller id and then the greater one using a CASE expression.

A: ; WITH CTE(ID,SENDER_ID, RECIEPENT_ID) AS
(
SELECT 1,23,20  UNION
SELECT 2,11,5   UNION
SELECT 3,20,23  UNION
SELECT 4,23,20  UNION
SELECT 5,7 ,11
)
SELECT *, ROW_NUMBER() OVER (PARTITION BY ABS(SENDER_ID - RECIEPENT_ID) ORDER BY ID) RN  FROM CTE

FROM THIS USE WHERE RN = 1

A: CREATE TABLE messages
(
    id int,
    sender_id int,
    recipient_id int
)

INSERT INTO messages
VALUES
    (1,23,20),
    (2,11,5),
    (3,20,23),
    (4,23,20),
    (5,7,11)

SELECT
    p.participant_1,
    p.participant_2,
    MIN(p.id)
FROM
(
    SELECT
        id,
        participant_1 = sender_id,
        participant_2 = recipient_id
    FROM  messages a
    WHERE sender_id <= recipient_id
    UNION ALL
    SELECT
        id,
        participant_1 = recipient_id,
        participant_2 = sender_id
    FROM  messages a
    WHERE sender_id > recipient_id
) p
GROUP BY p.participant_1,
         p.participant_2

A: Since the sender and recipient are both integer identifiers, how about concatenating them in a specific (e.g. ascending) order? For example:
SELECT
  CONCAT(CAST(MIN(sender_id, recipient_id) AS CHAR),
         '-',
         CAST(MAX(sender_id, recipient_id) AS CHAR)) AS pair,
  MIN(id) AS id
FROM messages
GROUP BY pair

This way we are guaranteed to get the lower number first, and higher number second, regardless of which one is sender/recipient.
Note, if you wanted the output you requested, you would simply need to join the messages table with the above on id just to get the exact rows.


text:
Q: Optimising asyncronus HttpClient requests I have made a class to handle multiple HTTP GET requests.  It looks something like this:
public partial class MyHttpClass : IDisposable
{
    private HttpClient theClient;
    private string ApiBaseUrl = "https://example.com/";

    public MyHttpClass()
    {

        this.theClient = new HttpClient();
        this.theClient.BaseAddress = new Uri(ApiBaseUrl);
        this.theClient.DefaultRequestHeaders.Accept.Clear();
        this.theClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    }

    public async Task<JObject> GetAsync(string reqUrl)
    {

        var returnObj = new JObject();
        var response = await this.theClient.GetAsync(reqUrl);

        if (response.IsSuccessStatusCode)
        {
            returnObj = await response.Content.ReadAsAsync<JObject>();
            Console.WriteLine("GET successful");

        }
        else
        {
            Console.WriteLine("GET failed");
        }

        return returnObj;
    }
    public void Dispose()
    {
        theClient.Dispose();
    }
}

I am then queueing multiple requets by using a loop over Task.Run() and then after Task.WaitAll() in the manner of:
public async Task Start()
{
    foreach(var item in list)
    {
        taskList.Add(Task.Run(() => this.GetThing(item)));
    }
    Task.WaitAll(taskList.ToArray());
}

public async Task GetThing(string url)
{
    var response = await this.theClient.GetAsync(url);

    // some code to process and save response

}

It definitiely works faster than synchonus operation but it is not as fast as I expected.  Based on other advice I think the local threadpool is slowing me down.  MSDN suggest I should specify it as a long running task but I can't see a way to do that calling it like this.
Right now I haven't got into limiting threads, I am just doing batches and testing speed to discover the right approach.
Can anyone suggest some areas for me to look at to increase the speed?

A: So, after you've set your DefaultConnectionLimit to a nice high number, or just the ConnectionLimit of the ServicePoint that manages connections to the host you are hitting:
ServicePointManager
    .FindServicePoint(new Uri("https://example.com/"))
    .ConnectionLimit = 1000;

the only suspect bit of code is where you start everything...
public async Task Start()
{
    foreach(var item in list)
    {
        taskList.Add(Task.Run(() => this.GetThing(item)));
    }
    Task.WaitAll(taskList.ToArray());
}

This can be reduced to
var tasks = list.Select(this.GetThing);

to create the tasks (your async methods return hot (running) tasks... no need to double wrap with Task.Run)
Then, rather that blocking while waiting for them to complete, wait asynchronously instead:
await Task.WhenAll(tasks);

A: You are probably hitting some overhead in creating multiple instance-based HttpClient vs using a static instance.  Your implementation will not scale. Using a shared HttpClient is actually recommended.
See my answer why - What is the overhead of creating a new HttpClient per call in a WebAPI client?


text:
Q: Copying a file from github I accidentally deleted a folder from a project. However, I pushed this folder on github and have it there. How can I retrieve this folder? (copy it from github to my local files).

A: You can try and restore the folder from your local history (which include the history that you have pushed to GitHub)
git checkout <treeish> -- /path/to/dir

Replace  with the SHA1 of the most recent commit where you can still see that folder.


text:
Q: .Net MemoryCache AbsoluteExpiration documentation is confusing When adding cache entry to System.Runtime.Caching.MemoryCache, you can specify CacheItemPolicy with AbsoluteExpiration. According to documentation (https://msdn.microsoft.com/en-us/library/Dd780607(v=VS.110,d=hv.2).aspx), AbsoluteExpiration is "The period of time that must pass before a cache entry is evicted".
Yes that's what I want - to specify "the period of time" after which my cache entry will expire. But AbsoluteExpiration is of type DateTimeOffset not TimeSpan, so it's a "point in time" not "period of time". How should I set it then? E.g. if I want the entry to expire in 60 sec, should I be setting AbsoluteExpiration to DateTimeOffset.UtcNow.AddSeconds(60)? Will I get the same result if I set it to DateTimeOffset.Now.AddSeconds(60)? Any reason to use one or the other?

A: Well yes, the phrase "after a specified duration" in documentation is a little bit confusing but DateTimeOffset type and AbsoluteExpiration property name leave no doubt.
As regards the way how to construct instance of a DateTimeOffset: there is no actually any difference in this case. DateTimeOffset.UtcNow.AddSeconds(60) and DateTimeOffset.Now.AddSeconds(60) will point to the same absolute time. These datetimes will differ by time zones but the moment of cache entry expiration will be the same in both cases. So there is no any reason to prefer one or another.


text:
Q: Android Sensors: Compass I'm currently working on a little compass app. So far so good, I got the compass working. I'm using the TYPE_ROTATION_VECTOR, since the result is much more stable than using TYPE_ACCELEROMETER combined with TYPE_MAGNETIC_FIELD. That's my code to calculate the azimuth:
SensorManager.getRotationMatrixFromVector(rotationMatrix, sensorEvent.values );
// original values are within [-180,180]
azimuth = (float) (Math.toDegrees(SensorManager.getOrientation(rotationMatrix, orientation)[0]) + 360) % 360;

If the device is laying flat on the table, the results are correct. If I lift my phone, so it's standing (the screen is facing to me now), I get incorrect results. I guess that's because my axes changed. How can i properly detect and handle this?

A: So as many code snippets and threads here suggests, we need some remapping of axis..
SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Z, remapped);

If I do this, the tilt won't influence the azimuth anymore. BUT, the pitch (lifting left or right side of the phone) will change the azimuth and I can't really figure out why.


text:
Q: Is the word "AS" in the mysql FROM clause optional? I stumbled across an interesting (to me) query, and I'm not really sure what it does.
SELECT SQL_CALC_FOUND_ROWS DISTINCT P.* FROM table P WHERE P.status = ...

The question is in regard to the P specifically FROM table P. I know in the FROM clause you can use an AS clause, but this particular query doesn't. Is the word AS optional?

A: Definining aliases isn't always optional, but when you do define an alias the keyword AS is always optional.
table_factor:
    tbl_name [PARTITION (partition_names)]
        [[AS] alias] [index_hint_list]
  | table_subquery [AS] alias
  | ( table_references )
  | { OJ table_reference LEFT OUTER JOIN table_reference
        ON conditional_expr }

Source: JOIN Syntax
The AS keyword is also optional when defining column aliases:

The AS keyword is optional when aliasing a select_expr with an identifier

Source: SELECT Syntax

A: In this situation it is not required, but there are other situations, such as joining derived tables, where it is required.

A: Historically the support was a little mixed but it's now a standard that everyone supports and is essential for name-conflict resolution (multiple tables being selected from with same named field[s]).  It's also really great for giving an alias to compound/calculated/virtual fields!
At the end of the day it's "required" if it would otherwise be unambiguous.


text:
Q: Is it possible to convert instance of a class to an instance of a subclass? I've recently came across a case where it would be very convenient to convert an instance of a class to a subclass, while the instance has been created within the parent class. But I've never seen such thing. So is there a way to do something like:
class Foo {
  var name: String
}

class Bar: Foo {
  var friendName: String
}

let foo = Foo(name: "Alice")
foo.toBar(friendName: "Bob")
// foo now of type Bar, as if I'd done
// foo = Bar(name: "Alice", friendName: "Bob")

If that's not possible, is there some reasons this would be impossible from a design perspective?
===edit=== description of a use case where it could make sense
Let say there's two views representing what correspond to the same database record for a book, on is a just a preview of the book and another is a more complex view. Models could be:
protocol BookMetaDelegate {
  func onReadStatusUpdate()
}

/// describe a book
class BookMeta {
  var delegate: BookMetaDelegate?
  private var _hasBeenRead: Bool
  var hasBeenRead: Bool {
    get {
      return _hasBeenRead
    }
    set {
      guard newValue != _hasBeenRead else { return }
      _hasBeenRead = newValue
      delegate?.onReadStatusUpdate()
    }
  }
  var title: String
}

/// contains all the content of a book
class Book: BookMeta {
  var content: BookContent
  var lastPageRead: Int

  /// some logic that only makes sense in a Book instance
  func getLastPageRead() {
    return content.getPage(lastPageRead)
  }
}

and views could look like:
class BookPreview: UIView, BookMetaDelegate {
  var book: BookMeta
  init(book: BookMeta) {
    book.delegate = self
  }
  func onReadStatusUpdate() {
    print("read status has changed! UI should update")
  }
}

class BookView: UIView {
  var book: Book
  init(book: Book) {
    book.hasBeenRead = true
  }
}

Then things could happen like
fetch(bookMetaWithId: 123).then { bookMeta in // bookMeta is of type BookMeta
  let preview = BookPreview(book: bookMeta)
  ...

  fetch(contentOf: bookMeta).then { content, lastPageRead in
    bookMeta.asBook(content: content, lastPageRead: lastPageRead)
    let bookView = BookView(book: bookMeta) // doing so will change the hasBeenRead flag and message the instance's delegate, ie the preview
    ...
  }
}

A: Thinking more about it, it sounds like that if such thing was possible, it'd break things like:
class Foo {
  var name: String
}

class Bar: Foo {
  var friendName: String
}

class Bla: Foo {
  var surname: String
}

func something(foo: Foo) {
  foo.toBla(surname: "Will")
}

let bar = Bar(name: "Alice", friendName: "Bob")
something(foo: bar) // what does that do ??? is bar a Bla now ?

so that'd be a good reason for making such casting impossible.


text:
Q: Maintaining iOS portrait orientation from a static library for one view controller only I know similar questions have been asked before, but this is a more specific use case (controlling orientation from a static library, cannot write in root view controller).
I have a static library which adds UI elements as overlays to a passed view controller (the client's root view controller) as subviews. Problem is our UI elements support portrait orientation only, while our client's application may support both portrait and landscape. This is fine, as long as our UI elements don't autorotate when our client's views do.
I'd like to lock the orientation to portrait only for our view controller only. In iOS 6, when I use the following code in my library's view controller, it doesn't affect the behaviour of autorotate at all:
-(BOOL)shouldAutorotate{
return NO;
}

-(NSInteger)supportedInterfaceOrientations{
    NSInteger orientationMask = 0;
    if ([self shouldAutorotateToInterfaceOrientation: UIInterfaceOrientationPortrait])
        orientationMask |= UIInterfaceOrientationMaskPortrait;
    return orientationMask;
}

When I put the same code in the root view controller, it works perfectly, with the app no longer auto-rotating. However, this is not an option for us since in production we will not have access to our client's root view controller. Is there a way to either lock view orientation from NOT a root view controller, or lock orientation for a single view controller only? Any other way of achieving what we need that I'm not thinking of? Hoping for solutions that work in iOS <= 6 if at all possible

A: You can't lock orientation only for one view controller in whole application . So you have to set transform angle with parent view frame on view launch and on change of orientation.
You add code for those view controller class
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
    [[self view] setBounds:CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width)];
    CGFloat radians = atan2f(self.view.transform.b, self.view.transform.a);
    if (radians!=M_PI_2) {
        [[self view] setTransform:CGAffineTransformMakeRotation(M_PI_2)];

    }

}

}

*

*(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
   [[self view] setBounds:CGRectMake(0, 0, self.view.frame.size.height, self.view.frame.size.width)];
    CGFloat radians = atan2f(self.view.transform.b, self.view.transform.a);
    if (radians!=M_PI_2) {
        [[self view] setTransform:CGAffineTransformMakeRotation(M_PI_2)];
}

}else{
[[self view] setBounds:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    CGFloat radians = atan2f(self.view.transform.b, self.view.transform.a);
    if (radians!=0) {
        [[self view] setTransform:CGAffineTransformMakeRotation(0)];
}

}
}


text:
Q: Give every prefab his own speed Is was building a star background simulation for a spaceshooter game in UNITY3D.
In c# i built The Instantitiation of prefabs which look like dots. While the generation of multiple dots on random spots on the x-axis go perfectly i wanted to add one thing.
Random speed. The problem is that i don't know how to give every prefab his own speed en keep it instead of getting overwritten by the next randomnization.
backgroundloop.cs
using UnityEngine;
using System.Collections;

public class backgroundloop : MonoBehaviour {
    public GameObject star;
    public float spawnTime;
    private GameObject starPrefab;
    private float timestamp;
    //public float hoogte = Random.Range(-1.01f,1.1f);
    //public float rotationPrefab = transform.localEulerAngles.z;

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {
        if (Time.time > timestamp)  {
            starPrefab = Instantiate
            (star, new  Vector3(7,Random.Range(-5.0f,5.0f),0),
            Quaternion.Euler(0, 0, 0)) as GameObject;
            timestamp = Time.time + spawnTime;
            }
        }
    }

And the problem is in this script:
prefabMovement.cs
using UnityEngine;
using System.Collections;

public class prefabMovement : MonoBehaviour {
    float speed = Random.Range (-3f, -0.1f);

    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

        transform.Translate (new Vector3(-1f,0,0) * Time.deltaTime);
        if (transform.position.x < -6.8) {
            Destroy (this.gameObject);
        }
    }
}

A: Huh? So the speed is overwritten and eventually ends up being the same on all instantiated prefabs?
Maybe it helps if initialize the speed variable inside the Start method.


text:
Q: Date as X-axis in Excel Excel "latest" version (very recent at least, with the Ribbon interface, 2018).
Fighting with dates to be used as X-axis labels in a chart.
The data below came out of a Pivot table; when selecting it directly in the Pivot table it was not possible to use a "X-Y Scatter" type chart (OK button grayed out on attempt).
When using the Line type - the X-axis Label "Specify interval unit" (Right click the axis, select Format Axis, Select Axis Options, the Labels) has the option to enter a number between 1 and 255 - i.e. not related to date at all. A value of 6 is too low to display ONE date per month, a value of 7 skips months.
So to get further; copy the data to a fresh sheet and make new attempts:
Sticking to Scatter type, you can't get Dates for the X-axis, instead the NUMBERS that are used to store dates appears - 2017-01-05 equals 42687.0
How to get past this quirkyness?

-- Example datatable ---
TheDate Value
2017-01-05  31
2017-01-09  33
2017-01-20  36
2017-01-26  17
2017-01-27  19
2017-01-30  30
2017-02-10  67
2017-02-13  34
2017-02-15  1
2017-02-20  20
2017-02-23  13
2017-03-09  32
2017-03-14  31
2017-03-17  34
2017-03-21  22
2017-03-24  36
2017-03-27  34
2017-03-28  33
2017-03-29  3
2017-04-06  52
2017-04-18  36
2017-04-19  25
2017-04-24  32
2017-04-28  34
2017-05-15  34
2017-05-18  24
2017-06-02  35
2017-06-07  32
2017-06-14  33
2017-06-20  35
2017-06-21  34
2017-06-30  5
2017-07-05  34
2017-07-11  36
2017-07-12  36
2017-07-18  26
2017-07-19  31
2017-07-21  34
2017-08-21  35
2017-08-23  31
2017-08-25  34
2017-08-30  19
2017-09-04  32
2017-09-07  14
2017-09-14  36
2017-09-15  66
2017-09-18  1
2017-09-20  35
2017-09-26  63
2017-10-04  15
2017-10-09  35
2017-10-12  17
2017-10-13  35
2017-10-18  35
2017-10-25  33
2017-10-27  47
2017-11-06  24
2017-11-22  25
2017-12-04  36
2017-12-06  11
2017-12-07  35
2017-12-11  71
2017-12-13  33
2017-12-14  22
2017-12-19  34
2017-12-20  13
2017-12-27  31

A: Make the chart data be external to any Pivot table, and make the type be "Line", ensure that the chart x-axis data is just dates - and the Axis type will show up as date, free to format in a reasonable manner for dates.