Q: MVC 3 DropDownList displays multiple values on Edit page I'm using an enum to populate my DropDownList that works fine with a List and Create views but my Edit view loads duplicate values in the DropDownList. The duplicate values are only the selected value for the property meaning, if Rented was the value saved in the DB the DropDownList would show Rented selected, Available, and another Rented in the list. What I need to know is how to load a DropDownList that selects the value previously stored in the DB for the PropertyStatus enum without any duplicates?
Controler:
        public ActionResult Edit(int id)
    {
        Property property = db.Properties.Find(id);

        ViewBag.PropertyStatus = SetViewBagPropertyStatus();
        return View(property);
    }

    private IEnumerable<SelectListItem> SetViewBagPropertyStatus()
    {
        IEnumerable<ePropStatus> values =
            Enum.GetValues(typeof(ePropStatus)).Cast<ePropStatus>();

            IEnumerable<SelectListItem> items =
             from value in values
             select new SelectListItem
             {
                 Text = value.ToString(),
                 Value = value.ToString()
             };
            return items;
    }

Model:
    public enum ePropStatus
    {
        Available ,
        Rented
    }

    public partial class Property
    {
         public int PropertyId { get; set; }
         public string PropName { get; set; }
         public string Address { get; set; }
         public string City { get; set; }
         public string State { get; set; }
         public string ZipCode { get; set; }
         public int SqFeet { get; set; }
         public int Bedrooms { get; set; }
         public int Bathrooms { get; set; }
         public int Garage { get; set; }
         public string Notes { get; set; }
         public ePropStatus PropertyStatus { get; set; }
    }

Edit View:
@Html.DropDownList("PropertyStatus", Model.PropertyStatus.ToString())

A: Try this instead :
@Html.DropDownListFor(model => model.PropertyStatus, ViewBag.PropertyStatus)

Edit ::: Alternately try this
Controler:
public ActionResult Edit(int id)
{
    Property property = db.Properties.Find(id);

    ViewBag.PropertyStatusList = SetViewBagPropertyStatus(property.PropertyStatus);
    return View(property);
}

private IEnumerable<SelectListItem> SetViewBagPropertyStatus(string selectedValue = "")
{
    IEnumerable<ePropStatus> values =
        Enum.GetValues(typeof(ePropStatus)).Cast<ePropStatus>();

        IEnumerable<SelectListItem> items =
         from value in values
         select new SelectListItem
         {
             Text = value.ToString(),
             Value = value.ToString(),
             Selected = (selectedValue == value.ToString())
         };
        return items;
}

View:
@Html.DropDownList("PropertyStatus", ViewBag.PropertyStatusList)


Q: find out windows in side-by-side mode The "View Side By Side" and "Synchronous Scrolling" made the comparison of 2 spreadsheets easier than ever. However, there isn't a "Synchronous Switching tab" feature, so if I switch to a different tab in one of the workbooks and continue scrolling, the sync'ed scrolling become quite funny.
Well, I shouldn't complain, because it's all done manually, and I should use this feature wisely.
As a lazy developer, I would like to write some code to dig myself out: Can I write a macro to automate the worksheet switching on the peer window in side-by-side mode?
It breaks down to 2 steps:

*

*how do I know if a window, most likely the ActiveWindow, is in side-by-side mode?

*if it is, how do I tell which window is its peer?

I did my homework. It seems Excel is not very programming friendly on this feature. There are 3 methods

*

*BreakSideBySide()

*CompareSideBySideWith(WindowName)

*ResetPositionsSideBySide()
and 1 Boolean property

*

*SyncScrollingSideBySide
on the Windows collection related to this feature, but are insufficient to solve my questions.
Does anyone have any idea how to achieve this? Or, is it indeed impossible? Thank you in advance.

A: You can achieve this using the Workbook_SheetActivate event:
http://msdn.microsoft.com/en-us/library/office/ff195710.aspx
if you put this code in your ThisWorkbook Object, then each time you change the active worksheet, it will...

*

*Cycle through all open workbooks with a different name

*Look for a worksheet with the same name as the sheet you just clicked on

*Activate the worksheet in the other Workbook
Private Sub Workbook_SheetActivate(ByVal Sh As Object)

    For i = 1 To Application.Workbooks.Count
        If Application.Workbooks(i).Name <> ThisWorkbook.Name Then

            Dim otherWB As Workbook
            Set otherWB = Application.Workbooks(i)
            otherWB.Sheets(Sh.Name).Activate

        End If
    Next

End Sub

Note that this requires the worksheet to exist in all open workbooks.  An error will result if it does not.  However, you could easily add error handling to ignore workbooks with unfound corresponding worksheets.
Also note that it's probably best to use this when only two workbooks are open.  I have not looked into the other methods you mentioned, but there may exist a way to identify the two workbooks that are currently in side-by-side mode, at which point the code could shed its for loop and become more concise.


Q: Android Datepicker Single Cell Color Hi I'd like to be able to choose a few dates in the month and change the color of it. Say in my application I want the dates 3, 4, 8  of September to be red so that the user would be able to know that at those specific dates there is already a submission. Is this possible, if so how? Thanks in advance!
edit. Ive tried searching the forums, searching other places, and have not been able to get an answer.
To make things clear, Im not just looking to change the color theme, Im looking to change the color of specific dates. Say the user has submitted something for the 8th of September. I want my application date picker to show that by changing the color of the number 8 in the datepicker window.

A: check the library to show date with the different colour themes:
Add to your styles.xml
<style name="MyDatePickerDialogTheme" parent="android:Theme.Material.Light.Dialog">
    <item name="android:datePickerStyle">@style/MyDatePickerStyle</item>
    <item name="android:colorAccent">@color/beautiful_color</item>
</style>

<style name="MyDatePickerStyle" parent="@android:style/Widget.Material.Light.DatePicker">
    <item name="android:headerBackground">@color/beautiful_color</item>
    <item name="android:datePickerMode">calendar</item>
</style>

Moreover, if you want to change the entire theme of the date picker, use the following dependency
dependencies {
    compile 'com.wdullaer:materialdatetimepicker:3.6.3'
}

You can use app:mcv_dateTextAppearance (or the Java setter) to do this. I don't have the full explanation, but for now, you can copy the default implementation and modify as you need. Essentially you need to supply a android:textColor that is a color state list with your desired colors.
Add a style:
<style name="TextAppearance.MyCustomDay" parent="android:TextAppearance.DeviceDefault.Small">
    <item name="android:textSize">12sp</item>
    <item name="android:textColor">@color/my_custom_day_color</item>
</style>

and create color/my_custom_day_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:enterFadeDuration="@android:integer/config_shortAnimTime"
    android:exitFadeDuration="@android:integer/config_shortAnimTime">

    <item android:state_checked="true" android:color="SELECTION_COLOR" />
    <item android:state_pressed="true" android:color="SELECTION_COLOR" />
    <item android:state_enabled="false"  android:color="#808080" />
    <item android:color="@android:color/black" />
</selector>

then set app:mcv_dateTextAppearance="@style/TextAppearance.MyCustomDay"


Q: Can I change JVM parameters during execution I am writing a Java program and at some point during execution I want to change the JVM settings (decrease the heap) and after a while increase it again. Is it possible with Java?

A: Long story short: you can't. Heap size is fixed once you are running it, and there's no way to modify it from the code.

A: I do not think this is possible, but you could of course control the heap with -Xmx or -Xms.
You can also play with : -XX:MaxHeapFreeRatio : this is the maximum percentage (70 by default if I am no mistaken) of the heap that is free before GC will shrink it.
Giving a small -Xms will make the heap grow (if needed and will involve a full GC) and shrink back is possible also.
Generally people try to avoid as much as possible this shrinking and growing because it involves a gull GC aka stop-the-world events that will slow you down.


Q: Why does node.js don't find the function if the files requires each other Here is my situation:

*

*file a.js require file b.js

*file b.js require file a.js

When I try to call a function which is in file b.js from file a.js then I get the exception that b.xy() is not a function.
If I remove the require in file b.js then node.js can find the function.
Why does node.js don't find the function if the files requires
each other?


Q: How to get relative path for logging.ini and log file in python over multiple OS I have created one wrapper logger class which actually wraps the functionality of logging module. I have created it so that every class in my application using logging doesn't need to add logging.config.fileConfig() and logging.getLogger() at the top every-time.
My wrapper class looks like this -
class MyFileLogger():
    # The config file for logging formatter.
    logging.config.fileConfig('logging.ini', disable_existing_loggers=False)

    def __init__(self, name):
        self.logger=logging.getLogger(name)

    def log_debug(self, message):
        self.logger.debug(message)

logging.ini file -
[loggers]
keys=root

[handlers]
keys=fileHandler

[formatters]
keys=myFormatter

[logger_root]
level=NOTSET
handlers=fileHandler

[handler_fileHandler]
class=handlers.TimedRotatingFileHandler
level=DEBUG
formatter=myFormatter
args=('testlog.log','midnight',)

[formatter_myFormatter]
format=%(asctime)s |%(name)-12s |%(levelname)-8s |%(message)s
datefmt=
class=logging.Formatter

MyFileLogger.py and logging.ini file resides on the same path. My intention to create testlog.log is also in same path as logging.ini file.
Implementation of the MyFileLogger.py would be like -
imp.py -
fileLogger = MyFileLogger(__name__)
message = "hey!"
fileLogger.log_debug(message)

Now this imp.py doesn't reside on the same path as MyFileLogger.py and logging.ini. That's why when I run it, this gives me below error cause the python is running at imp.py path.
  File "C:\Python34\lib\logging\config.py", line 76, in fileConfig
    formatters = _create_formatters(cp)
  File "C:\Python34\lib\logging\config.py", line 109, in _create_formatters
    flist = cp["formatters"]["keys"]
  File "C:\Python34\lib\configparser.py", line 937, in __getitem__
    raise KeyError(key)
KeyError: 'formatters'

I know if I just give an absolute path to logging.ini and testlog.log it will work. But I don't want to go there, since this application can be ran in Windows or in Linux. So there would be path problem.
Now even if I don't care about the Windows-Linux thing and only concentrate on the Linux. There is another problem. So if we assume the current directory structure as this ("ProjectDir/src" is added in PYTHONPATH and assuming there is __init__.py in every module folders)-
ProjectDir
├── src
│   └── sales
│       ├── common
│       │   ├── logger
│       │   │   ├── logging.ini
│       │   │   ├── MyFileLogger.py
│       │   │   └── testlog.log
│       │   └── implmnts
│       │       └── imp.py
│       └── unitTest
│           └── test_MyFileLogger.py
└── bar.txt

Let's assume:
imp.py -
fileLogger = MyFileLogger(__name__)
message = "From imp.py"
fileLogger.log_debug(message)

test_MyFileLogger.py -
fileLogger = MyFileLogger(__name__)
message = "from test_MyFileLogger.py"
fileLogger.log_debug(message)

Then if I run imp.py I need to change the logging.config.fileConfig('logging.ini', disable_existing_loggers=False) to logging.config.fileConfig('../logger/logging.ini', disable_existing_loggers=False)
After that it will run but when I try to run test_MyFileLogger.py I need to change again to logging.config.fileConfig('../common/logger/logging.ini', disable_existing_loggers=False)
So my code is dependent upon which file I am running which I want to get rid of. Is there any way I can dynamically get the path of logging.ini and testlog.log independent of which file(from other path) is invoking this? I don't want to hardcore the absolute path, since this needs to run in both Windows and Linux, any solution?


Q: String diff to show positions of changed characters? I'm looking for a way to diff two strings and return the index value of where the changes start and finish.
I'm already using diff-lcs to find out which lines have changed, but I need to figure out the positions of which characters have changed. I need the positions of the new characters so I can handle them with JavaScript, not the actual text, which is what most diff tools seem to give.
So, for example if I have this string:
The brown fox jumps over the lazy dog

and compare to this string:
The red fox jumps over the crazy dog

I would like to see something like:
[[5,8],[28,33]]

Those numbers being the position where the new characters are found.
Does anyone have any idea how I might get this done?

A: How about the Google diff-match-patch code? https://github.com/elliotlaster/Ruby-Diff-Match-Patch
I've used it in the past and been happy with the results.
Taken from the documentation linked above:
# Diff-ing
dmp.diff_main("Apples are a fruit.", "Bananas are also fruit.", false)
=> [[-1, "Apple"], [1, "Banana"], [0, "s are a"], [1, "lso"], [0, " fruit."]]

You would just need to iterate through the non-matches and find the character position in the appropriate string.
pos_ary = s.enum_for(:scan, /search_string/).map { regexp.last_match.begin(0) }


Q: Android studio/libGDX/admob cannot find dependecies() So I've been searching around for days trying to figure out why I can't implement admob into my Android Studio project.
Things I've tried:
I have the google play services installed and latest Android SDKs
File->Project Structure->ads->ticking admob
--this will try to load in the dependencies, and always fails with
(Error:Could not find method dependencies() for arguments [build_23ysmkvnpvbphbg3g4deijgq4$_run_closure6@4afc19b] on org.gradle.plugins.ide.idea.model.IdeaModel_Decorated@18b40be.)
I've tried deleting the .gradle folder, restarting AS and rebuilding with the same Error.
I've tried creating a new blank LibGDX project and importing that and directly getting the admob dependencies and still the same error message.
I'm honestly not sure what I'm overlooking here.
If there's any info you feel I've left out, please let me know.

A: So, I'm coming from the Eclipse environment, and whenever I built a libgdx project, I've never had to go into the "advanced" settings. so messing around some more I went into the advanced settings and saw a checkbox for IDEA(generates intellij IDEA project files) which has seemed to work in getting rid of that error.


Q: Scraping data from HTML to return to cells in Excel I am very new to coding. I know the basics, but I don't need that advanced of knowledge for my field--aside from this project.
I am attempting to search a license number on the AZ Medical Board website, click the search result to pull up a profile, and transfer the information on a profile to cells in Excel.
So far my code looks like this and it works perfectly (aside from the data scraping part)
Sub AZMDSearch()

Dim lastrow As Long
Dim Name2 As Object

lastrow = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row

For i = 1 To lastrow
Application.ScreenUpdating = False

Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate "https://gls.azmd.gov/glsuiteweb/clients/azbom/public/WebVerificationSearch.aspx"

Application.StatusBar = "Submitting"
While IE.Busy
    DoEvents
    Cells(i, 1).Select
    Selection.Copy
Wend
'**********************************************************************
With IE.document
delay 1
.getelementbyid("tbFileNumber").Value = Cells(i, 1).Value
delay 1
.getelementbyid("btnLicense").Click
delay 2
.getelementsbytagname("a")(0).Click
End With
'**********************************************************************

The code does exactly what I want it to do up until this point.
Now, here's what the HTML looks like for the data I want to transfer over:
Gabby Laub
MD

1234 S Pine
Scottsdale AZ 85258
Phone: (123) 456-7891

I need to be able to pull the Name (Gabby Laub) into Cell(i,2), the address part 1 (1234 s Pine) into Cell(i,3), address part 2 (Scottsdale, AZ) into Cell(i,4), and phone number into Cell(i,5).
I was working on something like this:
Set Name = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").innerHTML

But it doesn't work at all. I have been working on this project for weeks, and I would really appreciate some help. Obviously I'm aware that I am missing Next i and End sub.
Again, the ONLY part I need help on is how to actually get the data into Excel.
Thanks!

A: You could try something like:
Cells(i, 2).Value = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").getelementsbytagname("b").innerText

Cells(i, 3).Value = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnPracAddr").innerText

Since address1, address2 and phone would all be in Cells(i, 3) you might want to use to use text to column to split them into their appropriate columns.
Additionally you could create an array to store these data in if you're doing a bigger search. Then you could paste the array values into their cells after you've finished scraping, like:
searchInfo(i, 1) = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnEntName").getelementsbytagname("b").innerText
searchInfo(i, 2) = IE.document.getelementbyid("dtgGeneral_ctl02_lblLeftColumnPracAddr").innerText

Then after looping:
 For i = 1 to last row
       Cells(i,2).Value = searchInfo(i, 1)
       Cells(i,3).Value = searchInfo(i, 2)
 Next i

You'd still have the text to column issue but that can be solved pretty easily with some code in the loop. Specifics just depend on how the third column's values come out.
EDIT: Based on your comments below, this worked for me. It might take a little customizing, but this is the idea.
    ' remove .getelementsbytagname("a")(0).Click and replace with this
.location = .getElementsByTagName("a").getAttributes("href")


Q: Arduino IDE on Android tablet Hi am wondering if anyone knows of a IDE for my Android tablet that I can edit compile and upload sketches to my Arduino board via USB?

A: Really slow response, I know but once this gets out of beta phase it could work http://codebender.cc/

A: You can have Arduino IDE on android, but have some problem with the usb port
http://arduino.cc/forum/index.php/topic,114141.0.html
veckoff

A: Not that I know of, but maybe you could build something like it with this?
http://www.amarino-toolkit.net/

A: You can upload sketch, no root required:
http://arduinocommander.blogspot.com/2013/03/upload-sketch.html

A: Check out ArduinoDroid - full-featured Arduino IDE on android:
https://play.google.com/store/apps/details?id=name.antonsmirnov.android.arduinodroid


Q: Error in declaring data in rstan for graded response model I am trying to use Stan, specifically through rstan, to fit a graded response model. Luo and Jiao (2018), available here, provide Stan code for doing so. Here is their code, edited only to include more white space:
data{
    int<lower=2, upper=4> K; //number of categories
    int <lower=0> n_student;
    int <lower=0> n_item;
    int<lower=1,upper=K> Y[n_student,n_item];
}

parameters {
    vector[n_student] theta;
    real<lower=0> alpha [n_item];
    ordered[K-1] kappa[n_item]; //category difficulty
    real mu_kappa; //mean of the prior distribution of category difficulty
    real<lower=0> sigma_kappa; //sd of the prior distribution of category difficulty
}

model{
    alpha ~ cauchy(0,5);
    theta ~ normal(0,1);
    for (i in 1: n_item){
        for (k in 1:(K-1)){
            kappa[i,k] ~ normal(mu_kappa,sigma_kappa);
    }}
    mu_kappa ~ normal(0,5);
    sigma_kappa ~ cauchy(0,5);
    for (i in 1:n_student){
        for (j in 1:n_item){
            Y[i,j] ~ ordered_logistic(theta[i]*alpha[j],kappa[j]);
    }}
}

generated quantities {
    vector[n_item] log_lik[n_student];
    for (i in 1: n_student){
        for (j in 1: n_item){
            log_lik[i, j] = ordered_logistic_log (Y[i, j],theta[i]*alpha[j],kappa[j]);
    }}
}

However, when I try to use this code, the parser throws an error. Here is the R code to reproduce the error:
library("rstan")

n <- 100
m <- 10
K <- 4
example_responses <- sample(x = 1:4, size = n * m, replace = TRUE)
example_responses <- matrix(example_responses, nrow = n, ncol = m)

example_dat <- list(K = K,
                    n_student = n,
                    n_item = m,
                    Y = example_responses)

fit <- stan(file = "~/grm.stan", data = example_dat)

Here is the error I receive:
SYNTAX ERROR, MESSAGE(S) FROM PARSER:
 error in 'modelf6471b3f018_grm' at line 2, column 21
  -------------------------------------------------
     2:
     3: data {
     4:     int<lower=2, upper=4> K; // number of categories
                            ^
     5:     int<lower=0> n_student;
  -------------------------------------------------

PARSER EXPECTED: <one of the following:
  a variable declaration, beginning with type,
      (int, real, vector, row_vector, matrix, unit_vector,
       simplex, ordered, positive_ordered,
       corr_matrix, cov_matrix,
       cholesky_corr, cholesky_cov
  or '}' to close variable declarations>
Error in stanc(file = file, model_code = model_code, model_name = model_name,  :
  failed to parse Stan model 'grm' due to the above error.

I've tried going through the code and the Stan manual to see what the issue is with the data declaration, but I can't find a problem with it. The declaration appears to be very similar to a declaration example in the Stan Language Reference:
int<lower = 1> N;

Can anyone tell me what I'm missing?

A: Your code has non-standard characters in some of the white space, including right after K;


Q: how to take more than one photo in QML? I have to take 4 continues pictures using the webcamera in QML i can take only one picture after that
I get an error from the QML debugger which states "Camera not ready for capture" how do i get the camera to be in ready state after the first capture this is the code i have tried
even if i set the ready state to true: it does not seem to be working? is there an easy way to get my way around this?
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello World")
    Rectangle{
        width: parent.width
        height: parent.height
        ColumnLayout{
            width: parent.width;height: parent.height
            spacing: 15;
            Camera{
                id:cam
                captureMode: Camera.CaptureStillImage
                imageCapture {
                    onImageCaptured: {
                         ready:true
                        console.log(ready)
                    }

            }
            }
            VideoOutput{
                id:vid1
                source: cam
                height:parent.height
                width: 800
                Layout.fillWidth: true
                Layout.fillHeight: true

            }
            Rectangle{
                id:rect1
                width: 100
                height: 30
                Layout.fillWidth: true
                Layout.alignment:bottom
                color: "#365688"
                Text {
                    id: text1
                    anchors.centerIn: parent
                    text:"capture"
                    font.pointSize: 10
                }
                MouseArea{
                    anchors.fill:parent
                    onClicked: {
                        console.log("clicked");
                     for(var i=0;i<=3;i++){
                        cam.start()
                        cam.imageCapture.captureToLocation("C:/Users/vinay/Documents")
                        console.log(cam.cameraStatus)
                        }
                    }
                }
            }

        }
    }
}


Q: History.js bookmark support for HTML5 (pushState) and HTML4 (#) I've have the back and foward buttons working via History.js in both HTML5 and HTML4 browsers.
I'm now attempting to add bookmark support by parsing the url, and loading the content in the querystring.  The code I normally use to do this is:
var urlParams = {};
            (function () {
            var match,
                pl     = /\+/g,
                search = /([^&=]+)=?([^&]*)/g,
                decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
                query  = window.location.search.substring(1);

            while (match = search.exec(query))
            urlParams[decode(match[1])] = decode(match[2]);
            })();

This works great for the HTML5, but obviously does not work for the HTML4.   Whats a good way to parse the hash in HTML4, and the substring in HTML5?

A: found a solution on this page: https://getsatisfaction.com/balupton/topics/history_js_and_retrieving_state_from_a_url
"You can use this function however from one of my utility projects called jQuery Sparkle to do what you need: https://github.com/balupton/jquery-sparkle/blob/master/scripts/resources/core.string.js#L164
So you would do this:
var State = History.getState(), dataQuery = State.url. queryStringToJSON();"


Q: How can I search, display, and retrieve file using C manually by inputing the value first? #include <stdio.h>
#include <stdbool.h>

#define HASH_SIZE 10

int hash(int value);
void dfs(FILE *file, int value);

int main()
{
    FILE *file = fopen("DATA_FILE.csv", "r");

    if (file == NULL)
    {
        perror("Error while opening the file");
        return 1;
    }

    int value = -685434;

    dfs(file, value);

    fclose(file);

    return 0;
}

void dfs(FILE *file, int value)
{

    bool visited[HASH_SIZE] = { false };

    // Read the first value from the file
    int currentValue;
    fscanf(file, "%d", &currentValue);

    while (currentValue != value && !feof(file))
    {

        int key = hash(currentValue);
        visited[key] = true;

        fscanf(file, "%d", &currentValue);

        if (visited[hash(currentValue)])
        {
            fscanf(file, "%d", &currentValue);
        }
    }

    if (currentValue == value)
    {

        printf("Value found in file: %d\n", currentValue);
    }
}

int hash(int value)
{
    return value % HASH_SIZE;
}

While the instruction says,
"The data file has two pairs of columns, the first of which has the number you're seeking for and the second of which contains the paired numbers you need to retrieve and show.
In this instance, you need to use data scanning for the file by reading row by row to find the data
Here is what is expected to work from the code:
Your code receives input from command line arguments.
The format in command line as follow
find [-s | -t] number
description:
number : is the number that you must find inside the data file
[ … | …. ] : is the searching techniqye option that you need to choose one of the
parameters.
-s : you will search inside data file using file scanning row by row.
-t : you will search using your solution
Here is the input and output:

*

*find -s 12345
Found 12345 with data on second column is 987234
Time elapsed 200 ms
or

*find -t 12345
Found 12345 with data on second column is 987234
Time elapsed 1 ms

if an error occurs, it will say:
No method defined
Proper Syntax is
find [ -s | -t ] number

A: From my top comments ...

*

*From the problem description, the input [.csv] file is a series of lines of the form: key,value.

*Your code should be doing (e.g.): fscanf(file,"%d,%d",&curkey,&currentValue), so you are reading the file incorrectly.

*What you call value, I would call desired_key as it needs to match the key [and not the value] and if a match is found on the key, you want to print the value.

*You have to do this line-by-line if given -s as a command line arg.

*If given -t, you have to reading the file and store the key/value pairs in an array. You need a struct such as: struct row { int key; int value; };

*The problem statement doesn't mention a hash.

*I don't see a need for visited at all. To me, that's some extraneous code from a shortest path algorithm (e.g. Dijkstra's or A*).

*Your code doesn't look at argc/argv at all. So, you can't select the method from -s or -t and get the desired key value to search for.

Here is the corrected code. It is annotated:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int opt_s;
int opt_t;

// key/value item
struct keyval {
    int key;
    int val;
};

struct keyval *csvdata;                 // array of all pairs in file
int csvcount;                           // number of pairs in array

// method_s -- match on a line-by-line basis
int
method_s(FILE *file,int desired_key,int *retval)
{
    int curkey;
    int curval;
    int found = 0;

    // read all lines of the form:
    //   key,val
    while (fscanf(file,"%d,%d",&curkey,&curval) == 2) {
        found = (curkey == desired_key);
        if (found)
            break;
    }

    // return the value if a match
    if (found)
        *retval = curval;

    return found;
}

// load_t -- load up CSV array
int
load_t(FILE *file)
{
    int cap = 0;
    int curkey;
    int curval;
    struct keyval *pair;

    csvdata = NULL;
    csvcount = 0;

    while (fscanf(file,"%d,%d",&curkey,&curval) == 2) {
        if (csvcount >= cap) {
            cap += 10;
            csvdata = realloc(csvdata,sizeof(*csvdata) * cap);
            if (csvdata == NULL) {
                perror("realloc");
                exit(1);
            }
        }

        pair = &csvdata[csvcount++];
        pair->key = curkey;
        pair->val = curval;
    }

    // trim array to actual size used
    csvdata = realloc(csvdata,sizeof(*csvdata) * csvcount);
    if (csvdata == NULL) {
        perror("realloc");
        exit(1);
    }
}

// method_t -- match on a stored array basis
int
method_t(FILE *file,int desired_key,int *retval)
{
    struct keyval *pair;
    int found = 0;

    // load up the array
    load_t(file);

    // loop through the stored array, looking for a match
    for (int idx = 0;  idx < csvcount;  ++idx) {
        pair = &csvdata[idx];
        found = (pair->key == desired_key);
        if (found)
            break;
    }

    // return the value if a match
    if (found)
        *retval = pair->val;

    return found;
}

int
timems(void)
{
    struct timespec ts;
    long long nsec;
    static long long timebase = 0;

    clock_gettime(CLOCK_MONOTONIC,&ts);

    nsec = ts.tv_sec;
    nsec *= 1000000000;
    nsec += ts.tv_nsec;

    if (timebase == 0)
        timebase = nsec;
    nsec -= timebase;

    nsec /= 1000000;

    return nsec;
}

int
main(int argc,char **argv)
{
    int err = 0;

    --argc;
    ++argv;

    for (;  argc > 0;  --argc, ++argv) {
        char *cp = *argv;

        if (cp[0] != '-')
            break;

        if ((cp[1] == '-') && (cp[2] == 0))
            break;

        cp += 2;
        switch (cp[-1]) {
        case 's':
            opt_s = 1;
            break;
        case 't':
            opt_t = 1;
            break;
        default:
            err = 1;
            break;
        }
    }

    if (opt_s && opt_t)
        err = 1;

    if (! (opt_s || opt_t))
        err = 1;

    int desired_key = -1;
    if (argc != 1)
        err = 1;
    else
        desired_key = atoi(*argv);

    if (err) {
        printf("No method defined Proper Syntax is find [ -s | -t ] number\n");
        exit(1);
    }

    FILE *file = fopen("DATA_FILE.csv", "r");
    if (file == NULL) {
        perror("Error while opening the file");
        return 1;
    }

    int found = 0;
    int retval = 0;

    int msbeg = timems();

    do {
        if (opt_s) {
            found = method_s(file,desired_key,&retval);
            break;
        }
        if (opt_t) {
            found = method_t(file,desired_key,&retval);
            break;
        }
    } while (0);

    int msend = timems();

    fclose(file);

    if (found)
        printf("Found %d with data on second column is %d Time elapsed %d ms\n",
            desired_key,retval,msend - msbeg);

    return 0;
}

Here is the sample input (DATA_FILE.csv) file I used:
46079,96649
71463,62685
81995,47037
50876,79762
95492,88344
45272,72553
41950,80235
81543,99066
67329,78252
79563,36472
63549,83972
94173,58525
81532,25036
39514,94603
90454,25278
33306,95455
85052,5202
49451,58592
69333,80996
94039,34855

Here is the output for ./find -s 67329:
Found 67329 with data on second column is 78252 Time elapsed 0 ms

Here is the output for ./find -t 67329:
Found 67329 with data on second column is 78252 Time elapsed 0 ms

A: /* find_value.c */
#include <stdio.h>

int main()
{
    FILE *file;
    file = fopen("DATA_FILE.csv", "r");

    if (!file)
        {
            perror("DATA_FILE.csv");
            return 1;
        }

    int n;
    int find_value = 32;
        while(fscanf(file, "%d", &n) == 1) {
        if(n == find_value) {
            printf("%d\n", n);
        }
    }

        fclose(file);
        return 0;
}


Q: Add Google login to OpenIddict Authorization Server - who provides the client_id and how? Starting with the Zirku Sample of OpenIddict, I wanted to add Google Accounts as login provider (nuget: Microsoft.AspNetCore.Authentication.Google).
My changes include adding the google auth provider after AddOpenIddict(...):
services.AddAuthentication()
        .AddGoogle("Google", options =>
        {
            options.CallbackPath = "/signin-google";
            options.ClientId = "0000000000000-redacted.apps.googleusercontent.com";
            options.ClientSecret = "redacted";
            options.SignInScheme = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme;
        });

Adding /signin-google as valid authorization endpoint to allow calling SignIn:
options.SetAuthorizationEndpointUris("/connect/authorize", "/signin-google")
       .SetLogoutEndpointUris("/connect/logout")
       .SetIntrospectionEndpointUris("/connect/introspect")
       .SetUserinfoEndpointUris("/connect/userinfo");

However, when coming back from google, the OpenIddict Server always complans, that the client_id is missing:
fail: OpenIddict.Server.OpenIddictServerDispatcher[0] The authorization request was rejected because the mandatory 'client_id' parameter was missing.
Tried these config options already without any change:
options.AcceptAnonymousClients();
options.Configure(op => op.AcceptAnonymousClients = true);

What am I doing wrong?
complete log can be found here.
(and yes, I changed the port to 6001 to reuse an existing redirect-url registered at google)

A: options.AcceptAnonymousClients() has no effect on the code flow as client_id is a mandatory parameter in this case (it only affects the token, introspection and revocation endpoints).
options.SignInScheme cannot be set to a scheme belonging to OpenIddict. In most cases, it must correspond to a cookie handler (typically the one registered by Identity).
You will also want to remove /signin-google from the endpoints managed by OpenIddict, as it will prevent the Google authentication handler from working properly.


Q: Core animation (size change) with autolayout challenge I have a piece of core animation by use of 2 methods in order to give appearance that the object is growing in size from the centre-outwards from the existing location...
(1) viewDidLayoutSubviews()

self.imageView.frame = CGRectMake(187, 249, 0, 0)

which is in the centre of the screen for this imageView object
(2) viewDidAppear()
 - with animation block of duration 1 second. e.g.
UIView.animateWithDuration(1.0, delay: 1.5, options: [], animations: {

        self.imageView.frame = CGRectMake(16, 70, 343, 358)

        }, completion: nil)

which puts object where I want it to show in full size, for the specific screen size.
When I use the x and y coordinates for CGRectMake(...) on the iPhone size I'm looking for they work fine, But when I try on simulator with different screen sizes, it doesn't work in conjunction with the Autolayout constraints, but overrides the existing Constraints.
Question(s)...
Is there a way of making this animation work by centering it proportional to the screen size somehow, rather than explicit coordinates and sizes? via CGRectMake...? (...which seems to show a clash between use of Autolayout and Animation)
Ideally I'm looking for an elegant simple solution? or am I at the limits of the tech?
Many thanks in advance!

A: You can set imageView location using autolayout constraints & give it a size constraint and by taking an outlet from it you can animate height to increase leaving all other constraints working

@IBOutlet var myViewHeight: NSLayoutConstraint!
UIView.animateWithDuration(0.3, delay: 0.0, options: [], animations:
  {
      () -> Void in
        self.myViewHeight.constant = 300

        self.view.layoutIfNeeded()
        }, completion:nil)

You should take the outlet from the constraint itself like control+drag on Label.top = topMargin


Q: Integrating Lucene Index and Amazon AWS I have a an existing index of lucene index files and the java code to perform search functions on it.
What I would like to do is perform the same thing on a server so users of an app could simply pass a query that will be taken as an input parameter by the java program and run it against the existing index to return the document in which it occurs.
All the implementation has been tested on my local pc,but what I need to do is implement it in an Android app.
So far I have read around and concluded that porting the code in AWS lambda and using S3 to store the files and calling the s3 objects from lambda.
Is this the right approach?Any resources that point to the this approach or alternative suggestions are also appreciated.
Thanks in advance.

A: Every time your Android app sends a request to AWS Lambda (via AWS API Gateway I assume) the Lambda function will have to download the entire index file from S3 to the Lambda /tmp directory (where Lambda has a 512MB limit) and then perform a search against that index file. This seems extremely inefficient, and depending on how large your index file is, it might perform terribly or it might not even fit into the space you have available on Lambda.
I would suggest looking into the AWS Elasticsearch Service. This is a fully managed search engine service, based on Lucene, that you should be able to query directly from your Android application.

A: As you already have your index files in S3, you can direct your Lucene Index reader to point to a Location on S3.
String index = "/<BUCKET_NAME>/<INDEX_LOCATION>/";
String endpoint = "s3://s3.amazonaws.com/";
Path path = new com.upplication.s3fs.S3FileSystemProvider().newFileSystem(URI.create(endpoint), env).getPath(index);
IndexReader reader = DirectoryReader.open(FSDirectory.open(path))

You can either pass in client credentials in env or you can assign role to your Lambda function.
Ref:
https://github.com/prathameshjagtap/aws-lambda-s3-index-search/blob/master/lucene-s3-searcher/src/com/printlele/SearchFiles.java

A: For Lucene indices less than 512MB you can experiment with lucene-s3directory.
As Mark said, on AWS Lambda you are limited to 512MB on /tmp. I think having a completely serverless search service is very desirable but until that limit is gone, we're stuck with EC2 for production deployments. Once you go with running Lucene on EC2, storing the index on S3 becomes pointless as you have access to EBS or ephemeral storage.
In case you want to try out S3Directory, here's how to get started:
S3Directory dir = new S3Directory("my-lucene-index");
dir.create();
// use it in your code in place of FSDirectory, for example
dir.close();
dir.delete();


Q: Sequelize validation throwing error I'm trying to check that a username is unique, and I gather that I'd need a custom validation for that. I've written the following code, but instead of returning the error in the array returned by .validate(), it just throws the error, which isn't the behaviour described in the docs and isn't what I want.
var User = sequelize.define('User', {
    username: {
        type: DataTypes.STRING,
        validate: {
            isUnique: function (username) {
                User.find({ where: { username: username }})
                    .done(function (err, user) {
                        if (err) {
                            throw err;
                        }

                        if (user) {
                            throw new Error('Username already in use');
                        }
                    });
            }
        }
    },

A: The validation you are doing is asynchronous. You call the User.find method, and after that the validation method returns. Sequelize has no way of knowing that you are doing something async in your validation, unless you tell it so. Once your find call is done you throw the error, but the validation has completed, so there is no code to catch that error, which means the error is thrown and crashes the app
The way to tell sequelize that you are doing something async is to take a second argument  to your function, which is a callback. If you call the callback without any arguments, the validation succeeded, if you give it an argument, the validation failed.
var User = sequelize.define('User', {
username: {
    type: DataTypes.STRING,
    validate: {
        isUnique: function (username, done) {
            User.find({ where: { username: username }})
                .done(function (err, user) {
                    if (err) {
                        done(err);
                    }

                    if (user) {
                        done(new Error('Username already in use'));
                    }

                    done();
                });
        }
    }
},

Could you point me to the part of the documentation that mislead you, then we can hopefully correct it :)

A: Sequelize supports Promise style async operations. Specifically the Bluebird.js lib. Just change your function to specifically use the Promise -> next() pattern.
var User = sequelize.define('User', {
   username: {
    type: DataTypes.STRING,
    validate: {
        isUnique: function (username) {
            User.find({ where: { username: username }})
                .then(function (user) {
                    if (user) {
                        throw new Error('Username already in use');
                    }
                });
        }
    }
},

This will also handle any errors on User.find() for you.
See this example in their codebase
Of course the easiest way to handle unique constraints is by setting unique: true on the field definition itself:
var User = sequelize.define('User', {
  username: {
    type: DataTypes.STRING,
    unique: true
  },

But this requires that you are either creating the table using Sequelize or already have a table with the unique constraint set.

A: This question got a valid answer which explains how the validation option works. But in this situation you don't have to check if a user exists on your own.
Sequelizejs has a findOrCreate() method, that checks if somethings exists before doing anything.
Very useful method :)


Q: matplotlib says libpng16.so.16: cannot open shared object file: No such file or directory I am trying to install matplotlib version 2.0.0. I don't have root access, hence can't use sudo/apt-get When I tried installing matplotlib, it showed dependencies on freetype and libpng. So, I executed the following steps:
wget http://prdownloads.sourceforge.net/libpng/libpng-1.6.34.tar.gz
tar -xzf libpng-1.6.34.tar.gz
cd libpng-1.6.34/
./configure --prefix=/home/$username$/
make
make check
make install

cd ..
wget http://download.savannah.gnu.org/releases/freetype/freetype-2.5.3.tar.gz
tar xzf freetype-2.5.3.tar.gz
cd freetype-2.5.3
./configure --prefix=/home/$username$ --without-png
make && make install
export PKG_CONFIG_PATH=/home/$username$/lib/pkgconfig

pip install matplotlib==2.0.0

Which worked perfectly fine. But when I do import matplotlib.pyplot as plt it throws the following error:
ImportError: libpng16.so.16: cannot open shared object file: No such file or directory


Q: How to ensure that UINavigationController has finished animating before poping up another one? I make a program that push uinavigationcontroller. Once done it pop things back and then do something.
One of the thing it wanna do is wait until it finishes poping up before doing that something.
That's because one of the thing that it may do is to push another viewcontroller.
How should I do so?
I already create a category

-(void)SafelyPushController:(UIViewController *) pushee
{
    AssertMainThread;
    if([self.viewControllers lastObject]!=pushee){
        [self pushViewController:pushee animated:YES];
        while (false);
    }
    else{
        //DLog(@"Dont need to pushview");
    }

    while (false);
    //[self pushViewController:pushee animated:YES];
}

To prevent some of the cases.
I need more general solution.
Something like:
If navigationController is still animating, wait till it finish in background and do this block at current thread.
That kind of thing.

A: You need to use UINavigationController's delegate:
@property(nonatomic, assign) id<UINavigationControllerDelegate> delegate;

Set it to an object of a class that conforms to this protocol, which implements this method:
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated;

In this method you'll know when you have finished showing a view controller, thus if it was animated the animation has ended. Notice that if you push multiple view controllers you have to keep track of them.
Documentation:
UINavigationController
UINavigationControllerDelegate


Q: http_negotiate_language issue Perhaps I missed something but when I call
$result='';
      $langs = array(
          'en-US',
          'fr',
       );
var_dump(http_negotiate_language($langs,$result));

I have an 500 error message. Should I add some extensions, should I parametrize something on my php.ini ?

A: It is require PECL pecl_http >= 0.1.0


Q: xcode How to show $ value in a Label and a Text Box. Example 125000 as 125,000.00 I need to show $value on a Label.
currently it appears as 125000 but i need it to be 125,000.00
thanks in advance to all supporters.

A: Drag the Number Formatter (found in the object library) object onto the field/label.  Change the behavior (be sure your in the attributes inspector for the number formatter) to 'OS X 10.4+ Custom' (that's what it was in Xcode 4.5.2).
In the 'Integer Digits' field, change the minimum to 1 and leave the maximum whatever you need.  For the 'Fraction Digits' fields set the minimum and maximum to 2.
Near the top of the field, stick a dollar sign in front of the 'Format (+)' and '(-)' fields.
Check the group separator box then change the primary and secondary grouping fields to 3.

A: The solution of your problem is NSNumberFormatter
Some code to get you started:
    NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSLog(@"%@", [currencyFormatter stringFromNumber:[NSNumber numberWithInt:10395209]]);
[currencyFormatter release];


Q: Sending mail with embedded image in Ruby I want to send a mail with an attached image and embed this image in html. As a source for  tag , What should I write and is there any missing header parts such a content_type ?
When I am doing real test, I send to a mail to my gmail account. I can see there is an attachment with name "unnamed" and I could not display image even when I download.
Gem: Pony
require 'pony'
Pony.override_options = { :via => :test }
Pony.mail(
    :to => 'foo@bar',
    :from => 'abc@abc.com',
    :subject => 'test123',
    :body =>   "
Dear X, check the newsletter ,

 ",
    :attachments => {"happy_image.jpg" => File.read("happy_image.jpg")}
)
puts Mail::TestMailer.deliveries

output:
Date: Tue, 06 Dec 2016 17:23:05 +0300

From: abc@abc.com

To: foo@bar

Message-ID: <5846c9ca183d6_5983c9fd899060@MW7BIQ12TKYHQC.mail>

Subject: test123

Mime-Version: 1.0

Content-Type: multipart/mixed;

boundary="--==_mimepart_5846c9caf15a_5983c9fd8989e5";

charset=UTF-8

Content-Transfer-Encoding: 7bit

----==_mimepart_5846c9caf15a_5983c9fd8989e5

Content-Type: text/plain;

charset=UTF-8

Content-Transfer-Encoding: 7bit

Dear X, check the newsletter ,

----==_mimepart_5846c9caf15a_5983c9fd8989e5

Content-Type: image/jpeg;

 filename=happy_image.jpg

Content-Transfer-Encoding: base64

Content-Disposition: attachment;

filename=happy_image.jpg

Content-ID: <happy_image.jpg@MW7BIQ12TKYHQC>

/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQE

BQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/

2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQU

FBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wAARCAHiAuMDASIAAhEBAxEB/8QA

HwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF

BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkK

FhcYGQ==

----==_mimepart_5846c9caf15a_5983c9fd8989e5--

A: You should be able to BASE64 encode the image, and use the resulting string as the src of the img tag.
For example:

Also make sure that your content type is set as text/html instead of text/plain. Looking at the mail, it seems that it's set to the latter, hence why images don't render and tags render as text. Add the following to your arguments to use text/html content type:
:headers => { 'Content-Type' => 'text/html' }


Q: delete a DataTable row bound to a datagridview I have a DataTable bound to a dataGridView using the following code :
            dataGridView1.DataSource = ReducedColTable;

At some point i would like to move the selected rows into another Table.
So here is the loop :
   List<DataGridViewRow> rows = (from DataGridViewRow row in dataGridView1.SelectedRows
                                      where !row.IsNewRow
                                      orderby row.Index
                                      select row).ToList<DataGridViewRow>();
        foreach (DataGridViewRow item in rows)
        {
            DataRow newRow = dtarget.Rows.Add();
            newRow.SetField("artiste", item.Cells[0].Value);
            newRow.SetField("album", item.Cells[1].Value);
            newRow.SetField("song", item.Cells[2].Value);
            newRow.SetField("year", item.Cells[3].Value);
            newRow.SetField("file_path", item.Cells[4].Value);
            newRow.SetField("file_size", item.Cells[5].Value);
            dataGridView1.Rows.RemoveAt(item.Index);
        }

Ps : I didnt find a way to copy the row into the new table (dtarget) which is declared globally hence the approach col by col.
DataTable dtarget = new DataTable();

My issue is that the last line is removing the row from the DataGridView but not from the original table (ReducedColTable)
Any hint how to achieve this ?

A: I found that the DataTable’s ImportRow works well for this. If you set the grids SelectionMode to FullRowSelect then you should be able to loop through the grids SelectedRows collection and “import” the selected row(s) into the other DataTable. Below is a simple example.
dt and dt2 are two DataTables with similar schemas. dt is a data source for datagridview1 and dt2 is a data source to datagridview2. Initially, dt is filled with some data and dt2 is empty. Once the user selects one or more rows, a button's click event initiates moving the selected rows from dt to dt2.
To start, a simple loop through the selected rows. A check if the “new row” is selected which we do not want to copy, therefore we ignore it. Next, get the “data bound” row from the data table in the form of a DataRowView object. Then we “import” that row into dt2, and finally removing the copied row from dt. I did not do a lot of testing on this however it appears to work as expected.
private void button1_Click(object sender, EventArgs e) {
  DataRowView drv;
  foreach (DataGridViewRow row in dataGridView1.SelectedRows) {
    if (!row.IsNewRow) {
      drv = (DataRowView)row.DataBoundItem;
      dt2.ImportRow(drv.Row);
      dt.Rows.Remove(drv.Row);
    }
  }
}

To make the example complete, drop two grids and button onto a form.
DataTable dt;
DataTable dt2;

public Form1() {
  InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e) {
  dt = GetTable();
  dt2 = GetTable();
  FillTable(dt);
  dataGridView1.DataSource = dt;
  dataGridView2.DataSource = dt2;
}

private DataTable GetTable() {
  DataTable dt = new DataTable();
  dt.Columns.Add("Col1", typeof(string));
  dt.Columns.Add("Col2", typeof(string));
  dt.Columns.Add("Col3", typeof(string));
  return dt;
}

private void FillTable(DataTable dt) {
  for (int i = 0; i < 10; i++) {
    dt.Rows.Add("C0R" + i, "C1R" + i, "C2R" + i);
  }
}

Hope this helps.


Q: Chrome on Windows triggers d3.zoom behavior on click I'm creating an interactive map using dc.js and d3.js. The map should support zooming and panning, so I'm using the d3.zoom behavior. I also want a function to run when I click areas on the map. The code works as expected in Firefox (Linux and Windows), IE, and Chrome (Linux), but Chrome version 47 on Windows interprets the clicks as attempts to zoom, which suppresses the click events. Is there any way to avoid this?
I created a simplified jsfiddle to demonstrate the issue. The code is below:
HTML

JS
var container = d3.select('#container');
var fmt = d3.format('.2f');

var svg = container.append('svg')
    .attr('width', 400)
    .attr('height', 400)
    .append('g');

var colors = ['#444488', '#448844', '#884444'];

svg.selectAll('circle')
    .data(colors)
    .enter()
    .append('circle')
    .attr('cx', function(d, i) { return 50 + 100*i; })
    .attr('cy', function(d, i) { return 50 + 100*i; })
    .attr('r', function(d, i) { return 10 + 10*i; })
    .style('fill', function(d) { return d; })
    .on('click', function(d, i) {
        // Skip the click handler if preventDefault was called. This prevents the click
        // handler from running at the end of a drag.
        if (!d3.event.defaultPrevented) {
            console.log('clicked circle #' + i);
        }
    });

var zoomBehavior = d3.behavior.zoom()
    .scale(1)
    .scaleExtent([1, 15])
    .translate([0, 0])
    .on('zoom', function() {
        console.log('got zoom: scale = ' + fmt(d3.event.scale) + ', translate = [' + fmt(d3.event.translate[0]) + ',' + fmt(d3.event.translate[1]) + ']');
        svg.attr("transform", "translate(" + d3.event.translate + ") scale(" + d3.event.scale + ")");
    });

container.call(zoomBehavior);

The demo adds three circles to the SVG and gives each one a click handler. It also adds the d3.zoom behavior to the container element. I want it to do the following:

*

*Clicking a circle runs the cirlce's click handler.

*Using the mousewheel zooms in and out, whether the mouse is over a circle or the background.

*Clicking and dragging pans the area, whether the click/drag starts over a circle or over the background. If it starts over a circle, the circle's click handler shouldn't be run.

All these requirements are met by the demo in Firefox and IE. In Chrome, when I click a circle, the zoom handler runs instead of the click handler. Does anyone have suggestions for how to deal with this?
As another approach, I tried putting a rectangle either above or below the rest of the SVG elements and attaching the zoom behavior to the rectangle instead of the container, but I ran into various issues with events not reaching the correct element. I'm willing to explore that further if people think that's the way to go.

A: I experienced the same problem with an old version of d3 (3.3.3). I'm not sure if it's been fixed since. The problem, as you said, is that Chrome gets in a weird state where a mouse click triggers a mousemove event. Completely closing Chrome and reopening it seems to get it out of this state.
I was able to resolve the issue by checking in d3's mousemove function for actual movement. I added two lines to the moved() function within mousedowned() in d3:
function moved() {
    if(d3.event.movementX === 0 && d3.event.movementY === 0) // new
        return false; // new
    dragged = 1;
    translateTo(d3.mouse(target), l);
    zoomed(event_);
}

That seems to resolve the problem without having to restart Chrome.

A: My Chrome instance must have gotten into some strange state while I was developing and debugging. I restarted Chrome and tried again, and now it's working fine.


Q: Why is get_current_user_id() returning 0 when used in woocommerce_login_redirect hook I was searching now for a while to find a solution for my problem, where the function get_current_user_id() returns 0 when hooked to woocommerce_login_redirect.
Right after the login-redirect there should always be an user-id, or am I getting s.th wrong here?
In my function.php file I have follwoing code:
add_action( 'woocommerce_login_redirect', 'ffaces_register_customer' );
add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer' );

function ffaces_register_customer( $user ) {

  $customerid = get_current_user_id();

  if ( $customerid == 0 ) {
    $redirection_url = get_permalink( wc_get_page_id( 'myaccount' ) );
    return $redirection_url;
    exit();
  }

  // more code working with $customerid

  return home_url("my-account/my-projects");
  exit();
}

A: There are some mistakes in your code (the first function argument is not the user, but the url redirection to be filtered). Try the following instead:
add_filter('woocommerce_login_redirect', 'ffaces_register_customer', 10, 2 );
add_filter( 'woocommerce_registration_redirect', 'ffaces_register_customer', 10, 2 );
function ffaces_register_customer( $redirect, $user = '' ) {

    if( isset($user) && is_a( $user, 'WP_User' ) && $user->ID > 0 ) {
        return home_url("my-account/my-projects");
    } else {
        return get_permalink( wc_get_page_id( 'myaccount' ) );
    }

}

Code goes in functions.php file of your active child theme (or active theme). It should work.

A: I don't think its set yet when this fires.
The hook passes the user object of the user that logged in try to change
$customerid = get_current_user_id();
to
$customerid = $user->ID;


Q: Google Calendar API Sharing Example I am looking for examples of share calendar and share event using google calendar API in any programming language java, .net, java script.
Thanks,
Aqeel

A: I'm not sure how much this will help, but I have an example here using scala with the ical4j library to read a shared/public google calendar:
http://github.com/kevinwright/lsug-website/tree/master/src/main/scala/org/lsug/ical4scala/


Q: Can I DeserializeWithLengthPrefix a c# class into a Python class? I have a lot of data Serialized with ProtoBuf in c#.
A colleague would like read these files with Python.
Can this be achieved as Python classes not same as c#.
Here is the c# class:
   [ProtoContract]
    public class TickRecord
    {
        [ProtoMember(1, DataFormat = DataFormat.FixedSize, IsRequired = true)]
        public DateTime DT;
        [ProtoMember(2, DataFormat = DataFormat.FixedSize, IsRequired = true)]
        public double BidPrice;
        [ProtoMember(3, DataFormat = DataFormat.FixedSize, IsRequired = true)]
        public double AskPrice;
        [ProtoMember(4, DataFormat = DataFormat.FixedSize, IsRequired = true)]
        public int BidSize;
        [ProtoMember(5, DataFormat = DataFormat.FixedSize, IsRequired = true)]
        public int AskSize;
}

A: That looks like protobuf-net; fortunately, the library includes a tool to spit out the .proto schema for what it thinks of your model:
var schema = Serializer.GetProto<TickRecord>();

which comes out as:
message TickRecord {
   required bcl.DateTime DT = 1;
   required double BidPrice = 2 [default = 0];
   required double AskPrice = 3 [default = 0];
   required sfixed32 BidSize = 4 [default = 0];
   required sfixed32 AskSize = 5 [default = 0];
}

where bcl.DateTime is a protobuf-net complex data type described in "bcl.proto".
Frankly, I suggest changing your date-time to a long using unix time - it'll make things a lot simpler here. That gives you:
message TickRecord {
   required sfixed64 DT = 1 [default = 0];
   required double BidPrice = 2 [default = 0];
   required double AskPrice = 3 [default = 0];
   required sfixed32 BidSize = 4 [default = 0];
   required sfixed32 AskSize = 5 [default = 0];
}

which you can give to your colleague, and they can run protoc or whatever other platform/library tool they need for protocol buffers in their environment, and they should be set. The serialization format is intentionally cross-platform, so the data should work fine.

Note: *WithLengthPrefix works by wrapping the data in an outer shell. I need to see the exact parameters you are using to advise on how to advise your colleague.
Note: changing the DateTime to long is a breaking change; if you can't do that your colleague will have to look at bcl.proto (just Google it) and translate it into python.


Q: How to use JavaScript create a damping function? I'm writing a scrollbar plugin. When dragging, I want to simulate the function of Safari(IOS), that is, overflow is allowed after dragging to the edge. In fact, Safari (IOS) has an edge decreasing effect when dragging, that is, it will become more and more immobile. This effect seems to be realized by damping function ? I tried to search, but I didn't find a particularly suitable function. I found some relevant contents in this article : How UIScrollView works, but I don't understand OC and Swift, and I'm not very good at math. Can anyone help me. ಥ_ಥ
Here is the damping function provided by another article : drag damping, but in fact, it uses a piecewise function to achieve the damping effect. Although it will be faster, it is found after the test that it does not meet my needs. I hope to set the maximum target value clearly, but in this function, it cannot explicitly control the maximum value.
This is a screenshot of the project. At present, the dragged part has not been completed, but the wheel control part has been realized, and the overflow can also be realized. However, because there is no appropriate damping function, the increment after overflow seems very rigid.


Q: How I can print 'process status' in Django? In one of my views I have several steps and they use 5 or 7 minutes to finish totally, so I was wondering if there is a way to print the status of the view in the browser, like:
"Calculating models..."
"Post processing models..."
"Making DB..."
"Cleaning old tables..."
Is there a way to do that?
Thanks!

A: Such heavy duty should probably not be part of a django view. You might want to look into django celery for asynchronous task management.
However you can do something like that just fine by polling your server. The easy setup, use short polling (basically a javascript loop that triggers an ajax request to the server every i seconds, retrieving a status response* which you can use to show your user anything).
*You'll have to setup an url and function that calculates the status somehow or if you're using celery you can use it's asynchronous result


Q: How can I either post or pass data from website to object element inside it? I'm trying to pass data somehow from website to an object element which is contained inside it.
A brief example:
This is a test1.html example which is in https://domain.tld/folder1/test1.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">

$( document ).ready ( function () {
   $("#templates").on("change", function () {
[.... here I want to pass data to object element ...]
      $("#test").show();
   });
}
);

</script>
</head>
<body>

<label>Open object </label>
<select id="templates name="templates">
<option value="1">Template1</option>
<option value="2">Template2</option>
<option value="3">Template3</option>
</select>
<div id="test" style="display: none;">
<object type="text/html" data="https://domain.tld/folder2/editor.php">
</object>
</div>
</body>
</html>

test div element is opened full screen when select element is changed. I want to pass selected value to "https://domain.tld/folder2/editor.php" html code, because I need to make some custom details to it according to selected value. Is it possible?
Hope you can understand me.
Thank you so much for your help.
John

A: yes it is, you can use AJAX :
var dataIn = { someKey : "someValue" };
$.ajax({
   url : "https://domain.tld/folder2/editor.php",
   data : dataIn,
   success : function ( result ) {
        // do something with the response
   }
});

or $.get or $.post depending on what you need in your backend.


Q: LinkedIn API OAuth issue This is my first time using the LinkedIn API. I am using Python.
I am exactly following the steps listed here: https://developer.linkedin.com/documents/getting-oauth-token-python
Everything goes well until I try to get the PIN for the access token. I type into my browser: "https://www.linkedin.com/uas/oauth/authorize?oauth_token=" + oauth_token , and then I get the error "We were unable to find the authorization token."
I also tried to download the full code linked at the top of the page, but that goes to a "page not found".
Anyone have any insight as to why I can't get the access token PIN? Thank you.

A: I apologize for not seeing this sooner.  The code on that page has been restored and you can download it now without issue.
https://developer.linkedin.com/documents/getting-oauth-token-python
If it's still not working, please let us know (I'll check back here, or you can post in our forums).  I use essentially that exact code whenever I test our API so it should work.


Q: System.Data.SqlClient.SqlException: Incorrect syntax near ')' I am getting an error in my SQL command with which I am trying to retrieve values from a SQL Server database. It is showing a error in browser as mentioned in title. If I remove the brackets it shows error in AND operator
string jdate = (string)Session["jdate"];
string clas = (string)Session["class"];
string scode = (string)Session["scode"];
string dcode = (string)Session["dcode"];
cn = new SqlConnection(ConfigurationManager.ConnectionStrings["dummyConnectionString"].ToString());

// error shows up on this line
string slct = "SELECT Route.Route_Source, Route.Route_Destination, Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time, Schedule.Route_rate_Ad , Seats." + jdate +
              "Schedule.Sch_id FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id INNER JOIN Route ON Schedule.Route_id = Route.Route_id INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id WHERE (Route.Route_Source =" + scode + ") AND (Route.Route_Destination =" + dcode + ") AND (Seats.Class=" + clas + ") ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";

cn.Open();

SqlDataAdapter da = new SqlDataAdapter(slct, cn);
DataSet ds = new DataSet();
da.Fill(ds);

SearchView.DataSource = ds;
SearchView.DataBind();

A: You should use a parameterized query.
This would allow a more understandable query text, avoid simple syntax errors
(like the missing comma at the end of the first line (jdate)),
avoid Sql Injections and parsing problems with strings containing quotes or decimal separators
string slct = @"SELECT Route.Route_Source, Route.Route_Destination,
               Flight.Flight_Name, Schedule.Depart_Time, Schedule.Arr_Time,
               Schedule.Route_rate_Ad, Seats." + jdate + ", Schedule.Sch_id " +
               @"FROM Schedule INNER JOIN Flight ON Schedule.Flight_Id = Flight.Flight_id
                         INNER JOIN Route ON Schedule.Route_id = Route.Route_id
                         INNER JOIN Seats ON Seats.Sch_id = Schedule.Sch_id
                 WHERE (Route.Route_Source = @scode)
                    AND (Route.Route_Destination =@dcode)
                    AND (Seats.Class=@class)
                 ORDER BY Schedule.Depart_Time, Schedule.Arr_Time, Flight.Flight_Name";

cn.Open();
SqlCommand cmd = new SqlCommand(slct, cn);
cmd.Parameters.AddWithValue("@scode", scode);
cmd.Parameters.AddWithValue("@dcode", dcode);
cmd.Parameters.AddWithValue("@class", clas);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);


Q: Count cells by their color in Excel This question is simple: How can I update a total number count in Excel that decreases based on how many red X's there are in a given column.
Where this becomes too complicated for me: I have made macros to sort cells based on numbers or color. There are five different colors, each representing a different county in my area. I have a total for each county. (ex. yellow = 41, blue = 15, red...) and want to update each colors total respectively (by subtracting 1 for each X) IF there is an X in the completed column.
So issues:

*

*How to keep track of a row of cells, though they may be sorted three
different ways at any given time (Is there a permanent cell ID?).

*How to update a number count for just a certain range of cells of the
same color.

Attached is a picture of the top of the spreadsheet to better understand how this looks:

any help is greatly appreciated, my unfamiliarity with excel functions is probably the root cause of this problem.

A: Solution: This can be done without VBA if you can add the county name for each entry. Let's say, you are putting them into column J (see yellow cells in below picture).
Then, to count totals, simply use the COUNTIF function to get the total number of rows for a county and substract those who are marked "X" using the COUNTIFS function. In cell N2, I entered:
=COUNTIF(J:J,L2)-COUNTIFS(J:J,L2,H:H,"X")
Add the other county names below the existing ones in column L and copy the formula from N2 to the cells below.
Explanation: COUNTIF counts the number of rows that match one criterion. Here, we are setting the county name (L2 for the first county) and we are looking for it in column J. Next, we need the number of rows that match both the county and the completion state of "X". COUNTIFS will do the trick as it counts the number of rows that match two or more criteria. In this case, we want the number of rows of a given county (column J) and we want them to be the value of a value in column L ("Bronx" for N2, "Manhattan" for N3 etc.). The second criterion is their completion state (column H) which you want to be X (specified in the formula as "X"). You then substract the second from the first number.
Edit: By the way, sorting does not affect these formulas, they will continue to work.


Q: Can Deferred object chains be used on event handlers? I'm somewhat new to Javascript / jQuery (but not to programming), so please excuse any ignorance on this matter. I've already looked at this question and this one, but neither one solved my problem.
My scenario: I have a slideshow written in Javascript / jQuery. In this slideshow, I would like show the controls (play button, backward, forward) when the user hovers over the slide and hide them when the mouse leaves the slide area. The buttons show and hide as expected, but when I hover over one of the buttons (which are also over the slideshow) it disappears (which I know is because of "mouseleave" on the slide).
I tried adding hover event handlers to my buttons to change a global boolean so that the slideshow controls will only be hidden if that boolean is false (meaning the "mouseenter" for one of the buttons wasn't fired). I then registered the "mouseenter" event before the "mouseleave", but it didn't work.
Here's the problem: Despite the "mouseenter" event for the button being fired before the "mouseleave" event for the slide, the event handler callbacks are executed in the opposite order. I'm not entirely sure why this is happening, but I know that it has to do with how hover events are handled in Javascript.
I read a little bit about Deferred objects and I'm wondering if this might be the right way to go about this?
The syntax is incorrect, but I'm thinking something along the lines of:
function isMouseOverButton() {
    if(mouseEnteredButtonEvent()) {
        window.isOverButton = true;
    } else {
        window.isOverButton = false;
}

function hideControls() {
    if(!window.isOverButton) {
        //hide buttons
    }
}

$.when($("#slide").mouseleave()).then(isMouseOverButton()).then(hideControls());

Is there anyway to combine event handlers and deferred objects like this? Or, is there a better way than deferred objects?
EDIT: I just came across this, but I would prefer not to use a plugin to accomplish this.

A: Nope, this is not the way to do it!
When the mouse enters the slides, you show the controls, and when the mouse leaves the slides, you hide the controls, except if the mouse enters the controls.
To do this you'll use a small timeout and check if the mouse entered the controls before they are hidden away.
var timer;

$('#slide').on({
    mouseenter: function() {
        clearTimeout(timer);
        $('.controls').show();
    },
    mouseleave: function() {
        timer = setTimeout(function() { //don't hide them right away
            $('.controls').hide();
        }, 400); // set a timeout
    }
});

$('.controls').on({
    mouseenter: function() {
        clearTimeout(timer);  // if the mouse entered the controls,
    },                        // clear the timeout, keeping the controls visible,
    mouseleave: function() {
        timer = setTimeout(function() {
            $('.controls').hide();
        }, 400);
    }
});

FIDDLE
A much easier way to do the same thing, would be to place the controls inside the #slide element in the HTML, that way they won't trigger the mouseleave event, but that's not always possible, or convenient.


Q: Link binary with static library in xcconfig I have an Xcode project that is essentially a single app that gets built into several almost identical targets. I have moved nearly all build configuration settings in central places, but I cannot figure out how to move linking against a static library (libMantle.a) to the xcconfig. I have tried the -framework and -l flags, like I'm using for various other libraries, but they don't work. Is there a way to get .a files out of the Link Binary with Libraries pane, so I don't need to keep all the targets in sync manually?

A: Figured it out...
Let's say you want to link against the file libGoogleAnalyticsServices.a. There are basically three things you should have in your .xcconfig to get it working.
First you want to make sure you have the path to the library in your search path. Then you need to pass two flags to make the linker happy -L with the path to the directory, and -l with the library.
Putting it all together will get you something like:
LIBRARY_SEARCH_PATHS = $(inherited) "$(SRCROOT)/Vendor/Google Analytics"
OTHER_LDFLAGS = $(inherited) -L"$(SRCROOT)/Vendor/Google Analytics" -lGoogleAnalyticsServices

(You would need to adjust for your relative paths)
The most helpful thing in getting this sorted out was the Log Navigator (command+8 in Xcode). By putting the static library in the Build Phases Link Binary With Libraries panel and doing a successful build, you can look details of the linker step in the logs, and see how it was passing the Analytics library to the compiler. From there it's just replicating those flags in the xcconfig.


Q: Indentation after chain of method calls Even though I should have the same setup as the rest of my team, Eclipse's formatter has one small anomaly in my setup.
You can see the difference in the attached picture.
On the left is my formatting.
On the right is the rest of the team's formatting.
I want to have the same formatting as the rest of the team.

The difference arises when there is an empty line after a chain of method calls.
Question: How do I achieve the formatting on the right?

A: I expect you are using the same formatter definition and have already tried to export the formatter on one of your team members machine and import it on yours.
Another thing you should check are the Save Actions in the preferences (Java -> Editor -> Save Actions). Maybe the settings for removing whitespaces differs here.


Q: How to print messages on console in Laravel? How do laravel print out some string on console when running php artisan serve?
I tried Log::info but it isn't working.

A: It's very simple.
You can call it from anywhere in APP.
$out = new \Symfony\Component\Console\Output\ConsoleOutput();
$out->writeln("Hello from Terminal");

A: You've to config where laravel to store the logs. Default Log::info() put the log in the log file not the console. you can use tail -f logpath to see the log.

A: Try with
error_log('message here.');

Read More

If You ant add LOG
Log::info('message');

If LOG with an array
Log::info(json_encode($array));

Import Illuminate\Support\Facades\Log;

A: Laravel 5.6 simplified this because you now have a logging.php config file you could leverage.
The key thing to know is that you want to output to stdout and php has a stream wrapper built-in called php://stdout. Given that, you could add channel for that wrapper. You would add the stdout "channel" to your channels that you will be logging to.
Here's how the config will basically look:
<?php

return [
  'default' => env('LOG_CHANNEL', 'stack'),

  'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['single','stdout'],
    ],

    'single' => [
        'driver' => 'single',
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
    ],

    'stdout' => [
        'driver' => 'monolog',
        'handler' => StreamHandler::class,
        'with' => [
            'stream' => 'php://stdout',
        ],
    ],
];

I have more information here - Laravel 5.6 - Write to the Console

A: You can call info() method
   $this->info("Your Message");


Q: What does 'G' do with sed command? I have tried two different sed commands against a text file called "file1.txt".
I have received the same result or output. What I don't understand is the meaning or use of "G" option! I have searched online, but I couldn't find a good answer!
Here are two commands:
sed 'G' file1.txt
sed '/^$/d;G' file.txt

Both commands give the same output! They create a one line gap between each line in the text file!
I know that'^$' refers to line containing nothing, but what does 'G' do. For example if I put 'd' instead of 'G' all blank lines will be deleted!

A: Get with g or G

Instead of exchanging the hold space with the pattern space, you can copy the hold space to the pattern space with the "g" command. This deletes the pattern space. If you want to append to the pattern space, use the "G" command. This adds a new line to the pattern space, and copies the hold space after the new line.

That is, instead of swapping the current contents of the hold and pattern space (current line, etc) you can take the pattern space and copy it into the hold space (either replacing or appending to the hold space in the process).
Those two sed commands are among the idiomatic sed one-liners that you can find online and they do the same thing only for certain files (those without blank lines in them).
 # double space a file
 sed G

 # double space a file which already has blank lines in it. Output file
 # should contain no more than one blank line between lines of text.
 sed '/^$/d;G'

A: According to the man sed:

*

*g
Replace the contents of the pattern space with the contents of the hold space.

*G
Append a newline to the contents of the pattern space, and then
append the contents of the hold space to that of the pattern space.


Q: TypeError: Cannot read property 'uid' of undefined This is my first javascript function for firebase.

TypeError: Cannot read property 'uid' of undefined

I got this error in firebase cloud function.How to resolve it?
const functions = require('firebase-functions');
    const admin = require('firebase-admin');
    admin.initializeApp(functions.config().firebase);

    exports.grantSignupReward = functions.database.ref('/users/{uid}/last_signin_at')
      .onCreate(event => {
        const uid = event.params.uid;
        admin.database().ref(`users/${uid}/referred_by`)
          .once('value').then((data) => {
            var referred_by_somebody = data.val();
            if (referred_by_somebody) {
              var moneyRef = admin.database().ref(`/users/${uid}/earned`);
              moneyRef.transaction((current_value)=> {
                return (current_value || 0) + 10;
              });
            }
            return console.log('reddem updated')
          }).catch(error => {
            console.log("Got an error: ",error);
          });
      });

A: The cloud functions were updated, therefore you need to change this:
 exports.grantSignupReward = functions.database.ref('/users/{uid}/last_signin_at')
  .onCreate(event => {
    const uid = event.params.uid;

into this:
 exports.grantSignupReward = functions.database.ref('/users/{uid}/last_signin_at')
  .onCreate(snap,context) => {
    const uid = context.params.uid;

more info here:
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database


Q: C# .net serial port receive buffer always emtpy I am trying to receive some data from a microcontroller connected to a windows PC through USB. I am doing this with the .net SerialPort functionality as you can see in my code below. I know the sleep is not very elegant but this is just my test code since I cannot get this to work.
Basically I have an Arduino sending some data which I can receive with the Arduino Serial Monitor, my c# program only outputs emtpy lines though, and the receive buffer is always emtpy. (the exact code you see here will output a zero and an emtpy line every second, even though a random number is sent every 200ms)
I already confirmed the baudrate is correct on both ends, I also switched over to a raspberry pi pico which had the same result.
I would really appreciate it if someone could help out here, as far as google is aware I must be the first one to run into this :D
using System;
using System.IO.Ports;
using System.Threading;

namespace serial_test
{
    class Program
    {
        static void Main(string[] args)
        {
            SerialPort testPort = new SerialPort("COM9", 9600);

            testPort.Open();

            while (true)
            {
                Thread.Sleep(1000);
                Console.WriteLine(testPort.BytesToRead);
                Console.WriteLine(testPort.ReadExisting());
            }
        }
    }
}

A: Instead of running an endless loop you may want to subscribe to the port's DataReceived event. You can then create a variable within the handler to read the data.
var port = (SerialPort)sender;
// Retrieve and write your data here

This may be easier to debug since you can place a breakpoint in the handler. If you never receive any data then you may have a handshake problem.


Q: Javascript function calling syntax (function($,window,undefined) {

    $.fn.simplyScroll = function(options) {
        return this.each(function() {
            new $.simplyScroll(this,options);
        });
    };

    var defaults = {
        customClass: 'simply-scroll',
        frameRate: 30, //No of movements per second
        speed: 2, //No of pixels per frame
        orientation: 'horizontal', //'horizontal or 'vertical' - not to be confused with device orientation
        auto: true,
        autoMode: 'loop', //auto = true, 'loop' or 'bounce',
        manualMode: 'end', //auto = false, 'loop' or 'end'
        direction: 'forwards', //'forwards' or 'backwards'.
        pauseOnHover: false, //autoMode = loop|bounce only
        pauseOnTouch: true, //" touch device only
        pauseButton: false, //" generates an extra element to allow manual pausing
        startOnLoad: false //use this to delay starting of plugin until all page assets have loaded
    };

Hi I'm pretty new to javascript and the syntax, especially function wise. How would I get the value of auto in the defaults object when it's wrapped in a function like this?
I know to get auto would just be defaults.auto, but since the function isn't named I'm not sure how to even get into it. I'm planning on changing the value at a later point in an external javascript file.

A: You cannot obtain this value if your code is outside of the function, unless this function stores the object in the defaults variable somewhere where it can be reached through a global variable.  This is due to the way that JavaScript functions work -- code external to the function has no access to that function's local variables.  (This is not very different from other programming languages.)
If your goal is only to change the value rather than obtain the default value, most jQuery plugins will allow you to pass in an object whose properties will override the default settings.  Based on the name of the plugin, you could do so like this:
$("#something").simplyScroll({
    auto: false
});

A: In my opinion, there are 2 ways that allows you to access to defaults object outside this function scope
1. In function scope, defaults object will be assigned to a propery of global object (= window)
...
// In the function scope
window.defobject = defaults;
...

For example:
(function($, window, undefined) {
    var defaults = {
        foo : "bar"
    };

    window.defobject = defaults;
})(jQuery, this);

console.print(defobject); // This is valid with no error

2. The function finally return this object as output
...
// In the function scope
return defaults;

For example:
var defobject = (function($, window, undefined) {
    var defaults = {
        foo : "bar"
    };

    return defaults;
})(jQuery, this);

console.print(defobject); // This is also valid with no error


Q: Cannot get websocket connection working with ec2 + application load balancer I am having trouble establishing a websocket connection. I have an aws ec2 instance that is running an SSL websocket server on a subdomain: api.example.com, on port 9999. My client application is running at www.example.com, the client sets up a listener:
new WebSocket('wss://api.example.com:9999');

This results in the browser giving me:

net::ERR_CONNECTION_REFUSED

So my next idea was since my application load balancer already has an https listener setup on port 443 going to my api server, I changed my websocket listener setup to:
new WebSocket('wss://api.example.com/socket');

Then I made my nodejs (restify) webserver on the ec2 instance catch /socket with plans to redirect it to localhost:9999...  However, I put a console.log in that /socket endpoint prior to redirecting, and there is no logging happening-- I also tried wss://api.example.com:443/socket, neither seems to hit the endpoint in my webserver.
Yet if I use curl, it works fine:
~>curl -i -N -H "Connection: Upgrade" -H "Upgrade: websocket" -H "Host: api.example.com" -H "Origin: https://www.example.com" https://api.example.com/socket
HTTP/2 301
date: Tue, 26 Jun 2018 02:27:07 GMT
content-type: application/json
content-length: 4
location: https://localhost:9999/localhost
server: restify
access-control-allow-origin: https://www.example.com
vary: origin
access-control-expose-headers: api-version, content-length, content-md5, content-type, date, request-id, response-time

although https://localhost:9999/localhost seems a little weird-- but regardless, when I use curl, it hits the endpoint and I see the log.


Q: Web API, API Controller and how to update a model? I'm trying out the API controller in MVC 4 and have a question about best practice when using put, updating an object.
I'm using RavenDB as data storage and I have created a custom MediaTypeFormatter that has a converter of type JsonDynamicConverter that can serialize and deserialize json to a dynamic object. With that said my API controllers Put method looks like this
 public void Put(string id, dynamic model) {}

this dynamic object looks sorta like this:
pageModel = {
  "id": "pages-2",
  "metadata": {
    "changed": "2012-02-28T17:16:27.323Z"
  },
  "parent": {
    "id": "pages-1",
    "slug": null
  },
  "children": []
}

so, so far so good but now I need to update my entity with id pages-2.
The UpdateModel does not exist in the ApiController so my question is what is the best/preferred way of doing this?

A: Simply call RavenDB to load the object with the appropriate ID, make the changes to its contents and persist it again.
No need to worry about any UpdateModel calls.  It doesn't apply here.
Be aware of one potential issue since you are including the id in the model. If I sent a PUT command to http://server/controller/pages-3 with that body what would happen?  You should probably send me a bad request response or something similar depending on how you want your API to work.

A: Is there any reason not to be explicit in your parameters? I would define an UpdateModel and take that as parameter instead of the dynamic. Then it also would be able to model validation.
ASP.NET WebApi includes handling of converting from both JSON and XML as input to your controller methods. I'm guessing your combination of custom mediatypeformatter and use of dynamic would be unneccesary in this case, if there is not something I'm missing.


Q: Route generator for 'item' was not included in parameters error Screenshot of error:

plunker (currently not working):
plnkr.co/edit/ft9Z4mq8C1llpAxA0Z1v?p=catalogue
Link to full project:
https://www.dropbox.com/s/0579y250pq5eti5/Project33.zip?dl=0
Full code of wiki.component.ts (code of page that causes error):
import { Component }        from 'angular2/core';
import { JSONP_PROVIDERS }  from 'angular2/http';
import { Observable }       from 'rxjs';
import { WikipediaService } from './wikipedia.service';
import {Router, RouteParams, RouterLink, ROUTER_DIRECTIVES} from 'angular2/router';

@Component({
  selector: 'Wikithing',
  template: `

Search and Display Page

Fetches after each keystroke

    <input #term (keyup)="search(term.value)"/>

{{item}}

 Price (in USD): $ {{item.price}}

 Availability: 24 hours

 Quantity currently in stock: {{quantity}}

 Image of item:

             Click here to bid on this item.
           <button (click)="gotoItem(item)">Click here to bid on this item.</button>

  `,
  providers:[JSONP_PROVIDERS, WikipediaService],
  directives: [ROUTER_DIRECTIVES, RouterLink],

})
export class WikiComponent {
  constructor (private wikipediaService: WikipediaService, private router:Router) {}
  items: Observable<string[]>;
  //  item: Item[] = [];

  search (item: string) {
    this.items = this.wikipediaService.search(item);
    this.items.map((items) => items.map(() => ({
      name: items,
      prices: Math.random(),
      quantity: Math.random(),
      availability: Math.random()
    })));

    var Prices = Math.random() + Math.random();
    var quantity = Math.random();
  }
  gotoItem (item: any) {
  this.router.navigate(['BiddingPage', {item: item}]);
  }
}

More information and context of problem:
stackoverflow.com/questions/37422205/displaying-data-that-is-consistent-with-search-results-on-a-different-webpage-t

A: Disclaimer: My english can be bad, sorry :c.
That is because in your @RouteConfig you have declarated that you need a item parametter like this:
{path: '/BiddingPage/:item', name: 'BiddingPage', component: BiddingPageComponent},

And in your template you doesn't have that parametter:
Click here to bid on this item.//the "item" is missing

Your template should be like this:
Click here to bid on this item.

Enjoy.


Q: Set size 'gridcolumn' by content in ExtJS I have a gridview with columns. Here example :
 {
     xtype: 'gridcolumn',
     header: '№',
     dataIndex: 'number'
 },

Is there any way to autosize column by content?
Thanks!

A: Yes just use the flex property.
Example:
column1 flex: 1  column2: flex: 1

|-----Column 1-----|-----Column 2-----|

column1 flex: 2  column2: flex: 1

|--------Column 1--------|--Column 2--|


Q: How to make Graph like below image in angular As I am New To Angular i am facing issue in Graph , I don't now how to make this in angular
Tried with Chart.js and Canvasjs In both i am facing problem
1. With Chart.js i was able to create static graph like below image, but i am not getting how to get data from API for this graph.
Note: I am Able to display any kind of data Using API , except Graph  So, Please Help me with this Graph thing.

LineChart = {};

  ngOnInit() {
    // Line chart:
    this.LineChart = new Chart('lineChart', {
      type: 'line',
      data: {
        labels: ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        datasets: [{
          label: 'Number of Items Sold in Months',
          data: [9, 7, 3, 5, 2, 10, 15, 16, 19, 3, 1, 9],
          fill: false,
          lineTension: 0.2,
          borderColor: 'white',
          borderWidth: 1
        }]
      },
      options: {
        title: {
          text: 'Line Chart',
          display: true
        },
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });

Note: I am Able to display any kind of data Using API , except Graph  So, Please Help me with this Graph thing.
Graph should Come

A: Before Initialising the Chart Object, fetch the data from the API and create the data array, then initialise the Chart Object.
If you want the graph to be continually changing, use Observables to get the data continuously and keep updating the charts.


Q: Getting component of stock market index from YQL Currently, I can get stock quote by returning xml and json using YQL console like
select symbol, price from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=IBM,YHOO,GOOG,MSFT&f=sl1d1t1c1ohgv&e=.csv' and columns='symbol,price,date,time,change,col1,high,low,col2'
I would like to get the complete component list from
http://download.finance.yahoo.com/d/quotes.csv?s=@^HSI&f=sl1d1t1c1ohgv&e=.csv
using YQL console, so I input the statement below in YQL console
select symbol, price from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=@^HSI&f=sl1d1t1c1ohgv&e=.csv' and columns='symbol,price,date,time,change,col1,high,low,col2'
but it said my link is invalid. Any thoughts and alterative solutions?

A: Your query was very nearly correct, but the URL was considered "invalid" as you noted. The solution is to properly escape the query string values.
http://download.finance.yahoo.com/d/quotes.csv?s=@^HSI&f=sl1d1t1c1ohgv&e=.csv

becomes
http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EHSI&f=sl1d1t1c1ohgv&e=.csv

Changing just those two characters into their %-encoded values allows YQL to pull back the CSV data.
select * from csv where url='http://download.finance.yahoo.com/d/quotes.csv?s=%40%5EHSI&f=sl1d1t1c1ohgv&e=.csv'

Aside: YQL doesn't like that the CSV has an empty line at the end of the file, this will cause issues when you try to use the columns where clause. If you're okay with having the columns called col<number> and want to skip the last (empty) row then use and col8 is not null at the end of your query.

A: This is the correct url:
http://quote.yahoo.com/d/quotes.csv?s=<symbol>&f=sl1d1t1c1ohgv&e=.csv
For Coca Cola:
http://quote.yahoo.com/d/quotes.csv?s=KO&f=sl1d1t1c1ohgv&e=.csv
Result: "KO",69.74,"9/2/2011","4:00pm",-0.71,69.7201,69.99,69.50,8765529
For HSI:
http://quote.yahoo.com/d/quotes.csv?s=^HSI&f=sl1d1t1c1ohgv&e=.csv
"^HSI",19616.40,"9/5/2011","4:01am",-596.51,19830.50,19830.50,19567.77,0
Here is an API document:
http://www.gummy-stuff.org/Yahoo-data.htm

A: The above solutions don't fully answer the question unfortunately, you will only get the first 51-52 results (the first page) and not the full index.
I don't think this is possible in raw YQL but you will need to write some code to get the HTML and then loop through each page of components and build your own datatable up from it.
I have tried a few ways and have a C# script that can do it, it would also be trivial to do this in Python and just load it into a pandas dataframe as you go along or just a plain list/tuple if all you want is the symbols to build up a component list for testing a portfolio against.
If people are still interested in this solution I can post the link to it.