text:
Q: how implement a foreach inside foreach that shows data in carousel using query? I'm using ASP.Net MVC5 with Razor engine, and I want to use a foreach in another foreach
@foreach(var item in Model.Table1)
 {
  ....
    @foreach(var item in Model.Table2)
    {
     ...Bootstrap Carousel
    }
}

outside foreach shows all items in Table1 but inside foreach shows some images in Table2.
I Don't know how do it :/
this is my code , but it don't work:
HTML:
@foreach (var item in Model.SubGoods)
{

modelNumber : @item.SubGoodModelNumber

Type : @item.SubGoodGender

@item.SubGoodName

@item.SubGoodInfo

 @item.NishtmanCode

            :ProductCode

//----------------------

            @foreach (var item1 in Model.GoodDetails)
            {

                if (item1 == Model.GoodDetails.FirstOrDefault())
                {

                 }
               else
                {

                }

//----------------------

}

Also I don't know where write query for some images in inside foreach
HomeController :
 public ActionResult Goods(int id)
    {
        HomeVM vm = new HomeVM();
        vm.SocialNetworks = blSocialNetwork.select();
        var goods = db.SubGoods.Where(p => p.FKMainGoodID == id).ToList();
        vm.SubGoods = goods;
        return View(vm);
    }

I want something like this :


text:
Q: Scheduling Criteria for Scheduling Policy can be subdivided into ? is this true what i wrote please thanks Scheduling Criteria for Scheduling Policy  can be subdivided into:
–

Non-preemptive scheduling.
Preemptive scheduling.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I extract the following patterns in java I have string in following format:
String s = " some text....
    [[Category:Anarchism| ]]
[[Category:Political culture]]
[[Category:Political ideologies]]
[[Category:Far-left politics]]
... some more text"

I want to extract all the categories from this text. [Anarchism,Political culture ....,Far-left politics]
Also, is there a good tutorial where I can learn about this regex pattern matching stuff..
Thanks

A: You can use the following regex to get categories:
\[\[Category:(.+)\]\]

Then you can access to your groups to get the category values.
Remember to add backslash to backslashes if you use on java strings:
\\[\\[Category:(.+)\\]\\]

You can see it working:

A: Assuming you don't want to select the  word "Category" itself, the regex would be:
(?<=Category:).*?(?=])

I'll break this down a bit for you.
The first bit in brackets looks for Category, without actually selecting it.
Next .+? looks for 1-infinity characters (other than a newline), but stops as soon as the next part is matched:
The final brackets tells it to look for a ], but without actually selecting it.
The results would be the bits below highlighted in blue.


text:
Q: Ordered sets and the least upper bound (1)  When we say $S$ is a partially ordered set (POSET) is this somewhat ambiguous unless we refer to the partial order we have in mind?  I.e. isnt is possible that S may be ordered differently according to our order relation?
(2) When we say $S$ has the least upper bound property do we also face the same issue as above?  e.g. for real numbers with least upper bound property, what is really meant is least upper bound property with respect to less than or greater than.
EDIT: DELETED Q3

A: When we say that $S$ is a poset, we usually are already referring to a specific order relation, that is, we actually mean $\langle S, \leq \rangle$ is a poset, where $\leq$ is any binary relation defined on $S$ which is reflexive, anti-symmetric and transitive.
So the partial ordering is often understood from the context, or from a previous reference to it.
The user JMoravitz gives in a comment a good example of two simple partial orderings on $\mathbb N$.
The idea that we mean that there can be defined a partial ordering on that set, I think it doesn't make much sense, because it is vacuous: for any set $S$, we can always define the poset $\langle S,=\rangle$.
It's an anti-chain, but a poset nonetheless.
It is also always possible to define a chain in any set (just take the anti-chain above, or any other ordering, and apply Szpilrajn Theorem).
When we say that a subset of $S$ has a least upper bound (or greatest lower bound) we are, of course, doing it with reference to the understood partial ordering.


text:
Q: why do i keep getting this error and how do i solve it So i have this massive python code but i cant get it to work. It keeps saying:
UnboundLocalError: local variable 'secondnum' referenced before assignment
This problem is actually solved now thanks for the help but the program still doesnt seem to work correctly. I dont get any errors but its supposed to be a stopwatch but i cant change the appearance of the sprites.
I tried to google it but no one seemed to have had the same problem as i did.
Please help. And Please have a bit patient with me im only 14
import pygame, sys
import time
import threading

secondnum = "0"
tensecondnum = "0"
minutenum = "0"
tenminutenum = "0"

secondimage = {"0": "0.png", 1: "1.png", 2: "2.png", 3: "3.png", 4: "4.png", 5: "5.png", 6:"6.png", 7: "7.png"
}
tensecondimage = {"0": "0.png"
}
minuteimage = {"0": "0.png"
}
tenminuteimage = {"0": "0.png"
}

def background():
    while True:
        global secondnum
        global tensecondnum
        global minutenum
        global tenminutenum
        time.sleep(1)
        secondnum = "1"

def foreground():
    global numbers1_group
    global numbers2_group
    global numbers3_group
    global numbers4_group
    global screen
    class Colon(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y):
            super().__init__()
            self.image = pygame.image.load("kolon.png")
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    class Numbers1(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y, number):
            super().__init__()
            self.image = pygame.image.load(number)
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    class Numbers2(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y, number):
            super().__init__()
            self.image = pygame.image.load(number)
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    class Numbers3(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y, number):
            super().__init__()
            self.image = pygame.image.load(number)
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    class Numbers4(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y, number):
            super().__init__()
            self.image = pygame.image.load(number)
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    # General setup
    pygame.init()
    clock = pygame.time.Clock()

    # Game Screen
    screen_width = 700
    screen_height = 350
    screen = pygame.display.set_mode((screen_width,screen_height))
    background = pygame.image.load("BG.png")
    pygame.mouse.set_visible(True)

    # Colon
    colon = Colon(350, 175)
    colon_group = pygame.sprite.Group()
    colon_group.add(colon)

    # Numbers1
    numbers1 = Numbers1(140, 175, tenminuteimage["0"])
    numbers1_group = pygame.sprite.Group()
    numbers1_group.add(numbers1)

    # Numbers2
    numbers2 = Numbers2(280, 175, minuteimage["0"])
    numbers2_group = pygame.sprite.Group()
    numbers2_group.add(numbers2)

    # Numbers3
    numbers3 = Numbers3(420, 175, tensecondimage["0"])
    numbers3_group = pygame.sprite.Group()
    numbers3_group.add(numbers3)

    # Numbers4
    numbers4 = Numbers4(560, 175, secondimage[secondnum])
    numbers4_group = pygame.sprite.Group()
    numbers4_group.add(numbers4)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        pygame.display.flip()
        screen.blit(background,(0,0))
        colon_group.draw(screen)
        numbers1_group.draw(screen)
        numbers2_group.draw(screen)
        numbers3_group.draw(screen)
        numbers4_group.draw(screen)
        clock.tick(60)

b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)

b.start()
f.start()

A: Please read https://stackoverflow.com/help/minimal-reproducible-example about asking better questions. Also, include the python version and the complete traceback when asking about an error.
In any case, the following shows what you did and the solution.
s = 0
def bad():
    s = s+1

def good():
    global s
    s = s+1

good()
bad()

prints
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    bad()
  File "<pyshell#7>", line 2, in bad
    s = s+1
UnboundLocalError: local variable 's' referenced before assignment

In 3.11, out in a month, the message is changed to "cannot access local variable 's' where it is not associated with a value", which we hope is clearer.

A: Python works that way, that if Python find a variable being assign in some function it defines this variable as local and stops looking for it to be assign somewhere out of the function. To fix it you better  make secondnum global inside of function background.
import pygame, sys
import time
import threading

global tensecondnum
global minutenum
global tenminutenum
secondnum = "0"
tensecondnum = "0"
minutenum = "0"
tenminutenum = "0"

secondimage = {"0": "0.png", 1: "1.png", 2: "2.png", 3: "3.png", 4: "4.png", 5: "5.png", 6:"6.png", 7: "7.png"
}
tensecondimage = {"0": "0.png"
}
minuteimage = {"0": "0.png"
}
tenminuteimage = {"0": "0.png"
}

def background():
    while True:
        global secondnum
        time.sleep(1)
        secondnum = str(int(secondnum) + 1)

def foreground():
    class Colon(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y):
            super().__init__()
            self.image = pygame.image.load("kolon.png")
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    class Numbers1(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y, number):
            super().__init__()
            self.image = pygame.image.load(number)
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    class Numbers2(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y, number):
            super().__init__()
            self.image = pygame.image.load(number)
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    class Numbers3(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y, number):
            super().__init__()
            self.image = pygame.image.load(number)
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    class Numbers4(pygame.sprite.Sprite):
        def __init__(self, pos_x, pos_y, number):
            super().__init__()
            self.image = pygame.image.load(number)
            self.rect = self.image.get_rect()
            self.rect.center = [pos_x, pos_y]

    # General setup
    pygame.init()
    clock = pygame.time.Clock()

    # Game Screen
    screen_width = 700
    screen_height = 350
    screen = pygame.display.set_mode((screen_width,screen_height))
    background = pygame.image.load("BG.png")
    pygame.mouse.set_visible(True)

    # Colon
    colon = Colon(350, 175)
    colon_group = pygame.sprite.Group()
    colon_group.add(colon)

    # Numbers1
    numbers1 = Numbers1(140, 175, tenminuteimage["0"])
    numbers1_group = pygame.sprite.Group()
    numbers1_group.add(numbers1)

    # Numbers2
    numbers2 = Numbers2(280, 175, minuteimage["0"])
    numbers2_group = pygame.sprite.Group()
    numbers2_group.add(numbers2)

    # Numbers3
    numbers3 = Numbers3(420, 175, tensecondimage["0"])
    numbers3_group = pygame.sprite.Group()
    numbers3_group.add(numbers3)

    # Numbers4
    numbers4 = Numbers4(560, 175, secondimage[secondnum])
    numbers4_group = pygame.sprite.Group()
    numbers4_group.add(numbers4)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        pygame.display.flip()
        screen.blit(background,(0,0))
        colon_group.draw(screen)
        numbers1_group.draw(screen)
        numbers2_group.draw(screen)
        numbers3_group.draw(screen)
        numbers4_group.draw(screen)
        clock.tick(60)

b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)

b.start()
f.start()


text:
Q: How to decrease quantity from database in item custom option I have some clothing items in different sizes such as small, medium or large.
Now I want to manage each stock separately e.g. small 15, medium 25, large 30 without using configurable product option. Using this method I added quantity field in custom option and add quantity in database.
Here is the link to add quantity in custom option in magento
Above link works perfect for me but the problem is arising on frontend, when we place an order of clothes in any size with any quantity, it will not decrease or update from our database.
What should I do so that quantity can be decreased from our database?
Any suggestions are very welcome! :)

A: This is crazy, a solution will be expensive and error-prone, I'd rather try to educate the client or look for alternative product management solutions.
But if you really want to try it, you will need to observe stock change for your pseudo-configurable-product and adjust your custom stock database accordingly. Observing stock change is a tricky problem, have a look at the answers here: Detect inventory change


text:
Q: Swift Error handling best practices Im used to typical try catch blocks to handle exceptions of any function or block of code like objective C.
However, after making leap of faith to Swift and reading about Swift's error handling; it's not much what I expected. You must handle your exceptions by throwing errors and guard and checking if else everything.
I need general Swift error handling tips and best practices, and especially for the following cases:

*

*Im using Alamofire for calling services, which has closure, and calling it through another function with closure too. AFAIK I can't throw error inside async code, so what is best practice for such case? will try to update with code sample

*Is it favourable to have every function in the app throw errors? Just in case ? Like checking every single value or result.

*Can I have a Singleton Error handling module?
Thanks in advance

A:
You must handle your exceptions by throwing errors and guard and checking if else everything.

This is an assumption that doesn't have to be true. If your code is structured correctly, you shouldn't have to check everything with if lets and throws.

I need general Swift error handling tips and best practices ...

Before you look at anything else, read the following pages in order. They should give you a good background on best practices.

*

*Error Protocol Apple Developer Documentation

*Error Handling - Apple's Swift Programming Language Guide

*Magical Error Handling in Swift - Ray Wenderlich

Im using Alamofire for calling services, which has closure, and calling it through another function with closure too. AFAIK I can't throw error inside async code, so what is best practice for such case?

You can. A good practice is to pass a closure as a parameter to your service-calling function, then call the closure when the asynchronous operation is complete, like so:
functionThatCallsAService(completion: @escaping (Data?, NetworkingErrors?) -> ()) {
    session.dataTask(with: request) { data, response, error in
        guard error == nil else {
            completion(nil, NetworkingErrors.returnedError(error!))
            return
        }
        completion(data, nil)
    }.resume()
}

enum NetworkingErrors: Error {
    case errorParsingJSON
    case noInternetConnection
    case dataReturnedNil
    case returnedError(Error)
    case invalidStatusCode(Int)
    case customError(String)
}

Is it favourable to have every function in the app throw errors? Just in case? Like checking every single value or result.

If you know for sure that a function or value won't be nil/cause a runtime error/throw an error, then don't check for it! But generally, according to the web pages above, you should check for nil and/or errors from calling a web service, interacting with the file system, creating a complex object, etc.

Can I have a Singleton Error handling module?

You technically can, but I don't see any reason to do so besides logging.

A: enum CheckValidAge : Error{
    case overrage
    case underage
}

func checkValidAgeForGovernmentJob(age:Int)throws -> Bool{
    if age < 18{
        throw CheckValidAge.underage
    }else  if age > 25{
        throw  CheckValidAge.overrage
    }else{
        return true
    }
}

do {
    try checkValidAgeForGovernmentJob(age: 17)
    print("You are valid for government job ")
}catch CheckValidAge.underage{
    print("You are underage for government job ")
}catch CheckValidAge.overrage{
    print("You are overrage for government job ")
}

try checkValidAgeForGovernmentJob(age: 17) OutPut : You are underage for government job
try checkValidAgeForGovernmentJob(age: 26) OutPut : You are overrage for government job
try checkValidAgeForGovernmentJob(age: 18) OutPut : You are valid for government job


text:
Q: How do you make a list view clickable I am trying to get this right, but this is getting me good. I have an example but i don't know  how it is working.
I got this much done.
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true" >
    </ListView>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="@string/welcome" />

</RelativeLayout>

now I think my problem is in this java file. The getListView thing is kicking me around. I think this is the answer but i just don't know how to get this right.
I think i know how to get it to work later.
    package com.example.boonehallfrightnightsapp;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    static final String[] CHOICES = new String[]
            {
                "Main House",
                "Nightmare",
                "Zombie Town",
                "Hayride",
                "Quit"
            };

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

         //found this part on an example
         //Set up ArrayAdaptor for the options
        setListAdapter(new ArrayAdapter<String>
            (this, android.R.layout.simple_list_item_1, CHOICES));
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        getListView().setTextFilterEnabled(true);

    }

    private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

     private void setListClickListener()
        {
            //Set up the click listener for the options
            getListView().setOnItemClickListener
            (
                new OnItemClickListener()
                {
                    //@Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
                    {
                        switch(arg2)
                        {
                            case 0: finish();
                                    break;
                            case 1: finish();
                                    break;
                            case 2: finish();
                                    break;
                            case 3: finish();
                                    break;
                            case 4: finish();
                                    break;
                            default: break;
                        }
                    }
                }//END OnItemClickListener
            );//END setOnItemClickListener
        }//END setListClickListener

}

A: You should extend ListActivity to call getListView() to get the ListView from the layout. You can check the documentation here - http://developer.android.com/reference/android/app/ListActivity.html (Class Overview > Screen Layout)


text:
Q: Android Canvas to Bitmap I have been searching online on how to turn what is on a canvas into a Bitmap. I have attempted multiple ways to do this like saving the drawing cache to a bitmap, but the end result is the background bitmap flashing on for a moment, then turning into a black screen. The test image is displayed over the background, but doesn't get overlaid by the background from the next calling of OnDraw.
MainThreading{

                        ...

              if(notuptodate == true){

                        //call readyBackground to create the background bitmap
                        this.mainPanel.readyBackground(canvas);
                        //post the canvas
                        surfaceHolder.unlockCanvasAndPost(canvas);
                        //clean the Canvas
                        canvas = null;
                        //ready new Canvas
                        canvas = this.surfaceHolder.lockCanvas();//lock the canvas to enable editing

                    }//if not true

                    if (MainThreading.notuptodate == false){

                        mainPanel.onDraw(canvas);

                    }//if false
...
                 }//mainthreading

    //this method is run first to create the Bitmap that on draw will use
    public void readyBackGround(Canvas canvas){

        if (MainThreading.notuptodate){
            //method used to draw multiple Bitmaps onto the canvas
            renderBackground(canvas);

            //private Bitmap, this is the supposed proper size of the bitmap
            backgroundBitmap=Bitmap.createBitmap(240, 320, Config.ARGB_8888);

            //set the canvas to turn whats on its self onto the bitmap.
            canvas.setBitmap(backgroundBitmap);

            //set boolean flag to false so renderBackground won't be called
            //untill it needs to be updated again
            MainThreading.notUpToDate = false;

        }

        //this method is called when notUpToDate = true
         @Override
    protected void onDraw(Canvas canvas){

        if (this.threado.getBackground() != null){
            canvas.drawBitmap(backgroundBitmap, 0, 0, null);

            }

            //this if statement is never activated
            if (this.threado.getBackground() == null){
                Log.d("background nonexistant", "Importante!");
            }
            //draw test object onto background
            test.DrawObject(canvas);

                //when MainThreading.notUpToDate = true isn't commented out, the
                //screen consistantly shows the background, but the test object isn't
                //drawn

        //MainThreading.notUpToDate = true;

        }

A: Try it this way...
- Create a bitmap of the correct size using Bitmap.createBitmap()
- Create a canvas instance pointing that this bitmap using Canvas(Bitmap) constructor
- Draw to the canvas
- Use the bitmap

A: public class CanvasToBitmap extends View {

    Paint paint = new Paint();
    Rect mRect = new Rect();
    Bitmap bitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);

    public myCanvas( Context context ) {
        super(context);
        Canvas canvas = new Canvas(bitmap);
        draw(canvas);
    }

    @Override
    public void onDraw(Canvas canvas) {

        mRect.set(0, 0, 200, 200);
        paint.setColor(Color.GREEN);
        paint.setStyle(Paint.Style.FILL);
        canvas.drawRect(mRect, paint);
        canvas.setBitmap(bitmap);

        ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
        try{
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, mByteArrayOutputStream);

            bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(mByteArrayOutputStream.toByteArray()));
            mByteArrayOutputStream.close();
       } catch (Exception e) {e.printStackTrace();}
    }
}

Create a new instance:
CanvasToBitmap canvasToBitmap = new CanvasToBitmap(getBaseContext());

Get bitmap of canvasToBitmap:
Bitmap bitmap = canvasToBitmap.bitmap;


text:
Q: liquibase:dropAll should also delete trigger functions I have a PostgreSQL Database that is setup using Liquibase. When I run liquibase:dropAll using maven it drop me everything but trigger functions. Is there a way that with that maven goal also triggerfunctions are dropped?
Since when I reapply my changeset after the dropAll it fails to create the already existing functions.

A: Unfortuantely no. The way dropAll is implemented is that it uses the liquibase snapshot function to find all objects to drop which works fine except for object types not looked for by snapshot. Snapshot handles standard types like tables, columns, views, and sequences but does not get into more database-specific types like triggers, functions, procedures, user defined types, etc. Since snapshot does not know about triggers, dropAll cannot know to drop them.
If you are using postgresql, the easiest way may be to just run
drop schema public cascade;
create schema public;

as described in "Drop all tables in PostgreSQL?" rather than use liqubase dropAll.


text:
Q: json standards for structure of responses I'm trying to decide on a standard for json responses for my applications going forwards.
So I'm thinking something along the lines of
Fake Json
    {
    Message:"hello, this is a reponse",
    action: 0 or 1, or "Good" or "bad",
    statusCode: 234,
    }
I'm wondering if there is a good standard for this already, and also how I can keep my standards in sync between my front and back end?
Is there a clever way to do this?

A: I'm using a structure similar to this:
{ status: ("ok", "error" or "redirect"), message: "some message goes here.", fields: "field selectors goes here in case some highlighting is needed", url: "url to open or redirect to if needed" }

*

*The status property is the key to tell what to do next;

*The message can be used to show a popup message or an inline message, etc. Can also be a list of messages separated by a '|' character to split;

*The field property is used to select (with jQuery or other JS library) the fields or other objects that need an action (think of this for field validation);

*The url property is used to change the page, open a popup or post something back, depending on your needs.


text:
Q: My bash script gets into infinite loop I want to read repository names from file, show YES-NO-CANCEL dialog and then add the repository if user answers YES. So far, I have written this code:
g_dlg_yes=1
g_dlg_no=0
g_dlg_cancel=127

show_confirm_dlg()
{
    local prompt="$* [y(es)/n(o)/c(ancel)]: "
    local resp=""
    while [ "$resp" != "y" ] && [ "$resp" != "n" ] && [ "$resp" != "c" ]; do
        echo "$prompt"
        read resp
    done
    if [ "$resp" = "y" ]; then
        g_dlg_res=$g_dlg_yes
    elif [ "$resp" = "n" ]; then
        g_dlg_res=$g_dlg_no
    elif [ "$resp" = "c" ]; then
        g_dlg_res=$g_dlg_cancel
    else
        g_dlg_res=$g_dlg_cancel
    fi
}

add_repo()
{
    local filename="/home/stojan/repo.list"
    while read -r line
    do
        local repo_name=$line
        echo "Name read from file - $line"
        show_confirm_dlg "Add repository $repo_name?"
        local rc=$g_dlg_res
        if [ $rc -eq $g_dlg_yes ]; then
            add-apt-repository -y $repo_name
            ##echo $repo_name
        elif [ $rc -eq $g_dlg_no ]; then
            echo "Repository $repo_name rejected"
        elif [ $rc -eq $g_dlg_cancel ]; then
            echo "Script cancelled"
            exit 1
        else
            echo "Unknown response. Now cancelling..."
            exit 1
        fi
        echo "Press ENTER..."
        read _

    done < "$filename"
}

add_repo

The problem is that when I run this script I get stuck at show_confirm_dlg() and get into infinite loop. That is the script doesn't wait for my input and repeats confirmation over and over again.

A: Using read reads from the standard input. When you use read inside a redirection, it doesn't read from the keyboard, it reads from whatever standard input is at that time.
C.f.:
{
    read a
    echo $a
} < <(echo Hello)

You can duplicate standard input somewhere else to be able to process several streams at the same time:
exec 3<&0          # fd3 now points to the initial stdin
{
    read a         # This reads the "Hello".
    read b <&3     # This reads from the keyboard.
    echo "$a, $b"

} < <(echo Hello)
exec 3<&-          # Close the fd3.

A: To get user input from the while...do loop, you can also do:
while [ "$resp" != "y" ] && [ "$resp" != "n" ] && [ "$resp" != "c" ]; do
    echo "$prompt"
    read resp </dev/tty
done

Please refer to this thread:
Read input in bash inside a while loop


text:
Q: How to match user defined data type in SQL I have a user defined data type CRM_IDS:
create or replace TYPE CRM_IDS AS VARRAY(10) OF VARCHAR(32);

In my table purecov_summary, the data type of column NAV_CRM_ID is CRM_IDS:
CREATE TABLE "PE_REG"."PURECOV_SUMMARY"
(
    ...
    "NAV_CRM_ID" "PE_REG"."CRM_IDS" ,
    ...
)

When I select the nav_crm_id of the first line with:
select nav_crm_id
from purecov_summary
where rownum = 1

I can get "PE_REG.CRM_IDS('10035005')".
But when I run:
select *
from purecov_summary
where nav_crm_id = PE_REG.CRM_IDS('10035005')

I get this error:

ORA-00932: inconsistent datatypes: expected - got PE_REG.CRM_IDS
  00932. 00000 -  "inconsistent datatypes: expected %s got %s"
  *Cause:
  *Action:
  Error at Line: 1 Column: 37

How can I select with PE_REG.CRM_IDS type?

A: The trick is to use nested varray column (nav_crm_id) within table keyword as table(nav_crm_id). So consider one of the following :
select p.*
  from purecov_summary p
 where exists (select column_value from table(p.nav_crm_id) where column_value = '10035005')

or
select p.*
  from purecov_summary p
  join table(p.nav_crm_id) c
    on c.column_value = '10035005';

Demo


text:
Q: regex failing with no errors I have the following text in a string called $test:
Content-Type: text/plain
Server: testapp (4.2.1 (x86_64/linux))
Content-Length: 125

{"password":"123","email_address":"","name":"j.doe","username":"jd123"}

I am trying to write a regular expression in php that will return everything after content-length: 125.
Here's what I have so far:
if (preg_match('/^Content\-Length\:[0-9\\n]+([a-zA-Z0-9\{\}\"\:])*/',$test,$result))
{
         var_dump($result[1]);
}

I don't get any error messages, but it doesn't find the pattern I've defined in my string.
I've also tried this pattern:
  '/^Content\-Length\:[0-9\\n]+([a-zA-Z0-9{}\"\:])*/'

where I tried to remove the escape char infront of the curly braces. But it's still a no go.
Can you tell me what I'm missing?
Thanks.
EDIT 1
my code now looks like this:
<?php
$test = "Content-Type: text/plain
Server: kamailio (4.2.1 (x86_64/linux))
Content-Length: 125

{"password":"test123","email_address":"","name":"j.doe","username":"jd123"}";

//if (preg_match('/Content-Length\:[0-9\\n]*([a-zA-Z0-9{}\"\:])*/',$test,$result))
//{
//         var_dump($result);
//}

preg_match('/({.*})/', $str, $matches);
echo $matches[0];
?>

That gives me the following error:

Undefined offset: 0 in /var/www/html/test/test.php on line 31

Line 31 is where I'm trying to echo the matches.

A: $str = <<<HEREDOC
Content-Type: text/plain
Server: testapp (4.2.1 (x86_64/linux))
Content-Length: 125

{"password":"123","email_address":"","name":"j.doe","username":"jd123"}
HEREDOC;

preg_match('/(\{.*\})/', $str, $matches);

echo $matches[0];

The regex here is simply matching a line that begins with { and ends with }. It's a quick and loose regex, however.

A: Instead of using a big pattern to match everything (which is timeconsuming) - why not use preg_split to cut your string into two pieces at your desired location?
$string = 'Content-Type: text/plain
   Server: testapp (4.2.1 (x86_64/linux))
   Content-Length: 125

   {"password":"123","email_address":"","name":"j.doe","username":"jd123"}';

$parts = preg_split ("/Content-Length:\s*\d+\s*/", $string);

echo "The string i want is '" . $parts[1] . "'";

Output:
The string i want is '{"password":"123","email_address":"","name":"j.doe","username":"jd123"}'

A: You can avoid the regex altogether because the HTTP header is always separated from the response body by 2 consecutives line breaks.
list($headers, $body) = explode("\n\n", $string);

Or for windows-style breaks( which by the way are the standard for HTTP headers):
list($headers, $body) = explode("\r\n\r\n", $string);


text:
Q: Storing a value from SQL database to a variable I tried this code to extract a single value from my database and store it in a variable. But it extracts the value Supplier ID instead of Quantity.
string query3 = "SELECT Quantity FROM Supplier WHERE [Supplier ID]='"+supplierid+"'";
SqlCommand cmd3 = new SqlCommand(query3, con);
con.Open();
string temporaryquantity = cmd.ExecuteScalar().ToString();
MessageBox.Show(temporaryquantity);

How can I extract Quantity instead of Supplier ID?

A: Your query will return the Quantity field... if you execute it. Your variable naming is unfortunate - you're creating cmd3 and executing cmd.
Execute cmd3, and your result will be as expected.


text:
Q: How do I convert a C# lambda expression into a delegate? I'm not very familiar lambda and delegate expressions, but I need to work with  .NET 2 framework so I will have to go with delegate.
Let's say I have an example of a
process = new Process();

and I want to pass additional parameters to the event by customizing it :
public void TestHandler(object s, DataReceivedEventArgs e, string mystring)
{
     Console.writeLine(e.Data + "," + mystring);
}
...

process.OutputDataReceived += new DataReceivedEventHandler((sender, e) => TestHandler(sender, e, "hello"));

How should I do this by using a delegate?
I tried to do this:
public delegate void TestDelegate(object s, DataReceivedEventArgs e, string mystring);

..eg inside main

TestDelegate testDel = delegate(object s,DataReceivedEventArgs e, string mystring) { TestHandler (s, e, mystring); };

process.OutputDataReceived += new DataReceivedEventHandler(testDel);

but I guess I'm wrong.

A: If I understand correctly, you can simply convert the lambda expression to a delegate (anonymous method expression), without creating a new delegate type.
Change this:
(sender, e) => TestHandler(sender, e, "hello")

Into
delegate (object sender, DataReceivedEventArgs e) {
    TestHandler(sender, e, "hello");
}

A: There's not a lot of context I can go of, but the signature for DataReceivedEventHandler is public delegate void DataReceivedEventHandler(object sender, DataReceivedEventArgs e);. It has two arguments and you're trying to pass a delegate with three arguments in there: (object s,DataReceivedEventArgs e, string mystring).
My guess is you'd have to remove the third argument, string mystring.


text:
Q: Change scrolling from whole page to single div On my webpage when I click an element, modal window (div with fixed position) shows up. Problem is, that when I am scrolling using mouse scroll (or using finger on my phone/tablet), whole page is scrolling, and I want scrolling to be applied to content of the div (it has scroll bar) and stop scrolling the page. When the div is hidden, I want scorlling to switch back to whole page. Is it possible?
I tried disabling scroll of body when I show div (jQuery):
$("body").css({"overflow", "hidden"})

but the only effect I get is that page scrollbar is being hidded, but still mouse scroll scrolls the whole page (behind the div I want to scroll).

A: Try looking into event bubbling so the parent scroll (body) isn't triggered when you try to scroll the div
https://api.jquery.com/event.stoppropagation/


text:
Q: python Gtk3 return value when button clicked I have a main python program A.py that calls a GUI Gtk python program, B.py, to display a window.
I want this window being color buttons and when I click on one, the main A.py code recover a value, the RGB color value.
A.py
import B
c = B.gui_color()
print(c)

B.py
class W(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="colors")
        self.box = Gtk.Box(spacing=0, homogeneous=True)
        self.add(self.box)

        colors = j.load("colors.json")

        for c in colors:
            b = Gtk.Button()
            b.connect("clicked", self.return_color, c["value"])
            # x257 to get the GTK color
            b.modify_bg(Gtk.StateType.NORMAL, Gdk.Color(c["value"][0] * 257, c["value"][1] * 257, c["value"][2] * 257))
            self.box.pack_start(b, True, True, 0)

    def return_color(self, widget, *color):
        self.close()
        return color[0]

def gui_color():
    w = W()
    w.connect("destroy", Gtk.main_quit)
    w.show_all()
    Gtk.main()

Everything is ok with the program, I get my window with multiple color buttons, however I can not figure out how to recover the color I clicked on. The return action in the return_color doesn't return to the A.py program. How can I perform that? Should I use stdout with print? I precise that after having clicking, I would like to do others actions that won't need a GUI at all.

A: Before return color[0] in the return_color do self.selected_color = color[0], after Gtk.main() do return w.selected_color


text:
Q: React - use single event handler to set state for multiple inputs? I'm new to React and wondering if it's possible to use a single event handler to set the state for many inputs. Namely, I'm not sure how to get the state "key" from the input into the handler, if that makes sense.
import React from 'react';

class User extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
    this.state = {
      id: props.id,
      firstName: props.firstName,
      lastName: props.lastName,
      email: props.email,
    };
  }

  // how do I (can I) use this single handler to independently change the state of multiple inputs?
  handleChange(e) {
    this.setState({ this.state.key // wrong!: this.inputRef.current.value });
  }

  render() {
    return (
      <div>
        <input type="text" ref={this.inputRef} id={`first_${this.state.id}`} value={this.state.firstName} onChange={this.handleChange.bind(this)} />
        <input type="text" ref={this.inputRef} id={`last_${this.state.id}`} value={this.state.lastName} onChange={this.handleChange.bind(this)} />
        <input type="email" ref={this.inputRef} id={`email_${this.state.id}`} value={this.state.email} onChange={this.handleChange.bind(this)} />
        // imagine ten more inputs
      </div>
    )
  }
}

A: What you're trying to do is more related to JS events handling.
handleChange(event) {
      const {name, value} = event.target;

      this.setState({
          [name]: value
      });
    }

*

*event.target is the element that fired that event (button, text area,
etc..) and you can grab whatever attribute you want from it (name,
type, value, etc..).

*Inside setState you've to use similar
states' names to that of your elements' names attribute. For the code
snippet you provided you can add a name attribute to the first input
tag <input name = "firstName" .... /> and so on.

*Having combinations of inputs of different types at the same time (e.g. text area and checkboxes) are trickier to deal with you might need to modify it a little or using conditions but you get the idea now :)

*One more thing don't bind your handlers inside the render() method beacuse with each render a brand new function returns one of the correct ways to bind the handlers is inside the constructor() method.


text:
Q: How to cycle through an array to find a button with a certain ID in vanilla JS? I'm making a project where I'm in a modal and want the user to change pen size.
I have the ID for every pen size, but I thought of making an array, loop through it, match with an ID and then from that ID give a lineWidth. But it turned out to be a bit difficult.
Here is my code, the thought behind this is to have four different sizes - each connected to each button.
JS:
let penModal = document.getElementById("pennstorlek--modal");
let penClose = document.getElementsByClassName("pennstorlek__close")[0];

let penSizeButton = document.querySelector(".width");
penSizeButton.addEventListener("click", () => {
  penModal.style.display ="block";

  let penButtonSmall = document.getElementById("pennstorlek--liten");
  let penButtonMed = document.getElementById("pennstorlek--mellan");
  let penButtonLg = document.getElementById("pennstorlek--stor");
  let penButtonGig = document.getElementById("pennstorlek--gigant");

  let pennButtons = document.querySelectorAll(".pennstorlek--button");

  if (toolDrawing.lineWidth === 5){
    toolDrawing.lineWidth = 10;
  }
  else {
    toolDrawing.lineWidth = 5;
  }
})

penClose.addEventListener("click", () =>{
  penModal.style.display ="none";
})

A: Try pushing penButtonSmall, penButtonMid, penButtonLg and penButtonGig into an array and then for loop through them using the .id property.
Something like this:
const sizes = [];
sizes.push(penButtonSmall);
//same for other 3 options.
for (i=0; i<4; i++)
{
 var x = sizes[i];
 if(x.id == "the_id_you_want")
 {//do something;
   }
}


text:
Q: failing to install and start windows service with winreg imported So I'm building a pretty simple service in python3.6. Client want's it to run on windows, so I'm using the win32serviceutil package to make a windows service. I install and package with pyinstaller and so far everything works great.
The issue I'm having is that the path differs between installing, starting and debugging. When installing and debugging, the path is the same as where I run the  command from. When starting the service however, the path is C:/windows/system32
The service needs to boot another .exe so it is important having an absolute path to the bundled application. I solved this by writing the path to registry when installing, and reading when starting the service. I do this using the winreg lib. It works great in debug mode, but it seems the service is run under another user when starting the service normally, and it fails to load somehow.
I get Error 1053 : The service did not respond to the start or control request in a timely fashion when running. Importing the winreg lib is fine, but when using it crashes with no error. I'm trying to catch the errors and print but I get nothing on command prompt or the Event Viewer.
Any help appreciated!!


text:
Q: Is it possible to run specific test case ([TestMethod]) from code using TestCategory or any other attributes? I know we can run specific TestMethods using Test Filter Criteria from TFS and console.  I am looking for a way to execute specific TestMethod from code as mentioned in here
Using Client API
TestRunCriteria runCriteria = CreateTestRunCriteria();
runCriteria.TestCaseFilter = "TestCategory=Nightly";

Is this possible? or is there any other way to execute the TestMethods from code.
And I am using MSTest not NUnit or XUnit.

A: Yes you can do that using TestCategory
Example :-
[TestCategory("Nightly"), TestCategory("Weekly"), TestCategory("ShoppingCart"), TestMethod()]
public void DebitTest()
{
}

Above code have many TestCategory and it can run as per the grouping of msTest
/testcontainer:"D:\NET_Workspace\automation\API.Test\TestMasterData\bin\Debug\API.Test.TestMasterData.dll" /category:Nightly /resultsfile:D:\Testcases_Reports\TestResult.trx

Now above command only run Nightly test group for you
From visual studio follow below steps :-
In your Test Explorer, right click and select "Group by -> Traits".

I have found one documentation for it too.
https://msdn.microsoft.com/en-us/library/dd286683.aspx
Hope it will help you :)

A: Try to use Name= <TestMethodDisplayNameName> condition. Related article: Running selective unit tests in VS 2012 using TestCaseFilter.


text:
Q: Entity Framework - Removing virtual keyword from navigation properties I am using entity framework with database first approach, along with EF 4.x DBContext Generator. All my entity classes have navigation properties which are marked as "virtual". I want to remove virtual keyword from all my entity classes. There are around 350 entity classes

A: You must modify T4 template (.tt) file to remove virtual keyword.

A: Removing virtual will mean that you are unable to use lazy loading for entity framework. In my opinion lazy loading has a very limited scope and is mostly misused (which often causes performance issues). However do note that when you turn it off you may need to adjust your code to manually load additional navigation properties when you retrieve data. You can do this by using .Include in your EF query
To remove the virtual flag you probably need to disable lazy loading in your EF generator.

A: You may want to try this VS extension, It adds (among other things) fine control over the virtual modifier:
EF Designer Extender


text:
Q: Sonarqube gradle analyzing project, task not found in root project Analysing project with this command
.\gradlew sonarqube \   -Dsonar.host.url=http://my.url \   -Dsonar.login=login --stacktrace

Getting this error

org.gradle.execution.TaskSelectionException: Task '\' not found in root project 'JavaLint'

And here is my gradle file
plugins {
  id "org.sonarqube" version "2.6.2"
}

apply plugin: 'application'
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'JavaLint'
version = '0.1-SNAPSHOT'
mainClassName = 'Main'

repositories {
    mavenCentral()
}

jar {
    manifest {
        attributes 'Main-Class': 'com.test.Run'
    }
}

sourceSets {
    main {
        java {
            srcDirs 'src'
        }
    }
 }

dependencies {
    compile group: 'commons-io', name: 'commons-io', version: '2.6'
    compile group: 'commons-lang', name: 'commons-lang', version: '2.6'
    compile group: 'org.jsoup', name: 'jsoup', version: '1.11.2'
    compile group: 'junit', name: 'junit', version: '4.12'
    compile group: 'log4j', name: 'log4j', version: '1.2.16'
}

Stack trace

I don't understand what am i supposed to do with it.

A: Thanks to the accepted answer by @ka whosyour above,I got my answer too.
Ok let me mention the details of how I was doing for an Android project in Android Studio and what I figured out after my research.
From the command generated by the Sonar Dashbaord, it is
./gradlew sonarqube \-Dsonar.projectKey=LetsGo \-Dsonar.host.url=http://localhost:9000 \-Dsonar.login=53689e9ceab73b3e8a76007d7953af3e9e2b2052
But, for Windows machine it should actually be:
gradlew sonarqube -Dsonar.projectKey=LetsGo -Dsonar.host.url=http://localhost:9000 -Dsonar.login=53689e9ceab73b3e8a76007d7953af3e9e2b2052
This worked like a charm for me.
Notice the Backwards slashes \ which are not needed on the windows machine.
Also, ./gradlew works in mac and gradlew on windows

A: It looks like you're using cmder (it's so beautiful) which means you're on Windows.  For Windows you'll want to provide the arguments to gradle as follows
./gradlew sonarqube -D "sonar.projectKey=<your_project_name>" -D "sonar.host.url=http://localhost:9000" -D "sonar.login=<your_project_token>"

A: Make sure first the directory contains gradle.build.
The command for windows :
./gradlew sonarqube -D "sonar.projectKey=your_sonarqube_key" -D "sonar.host.url=http://localhost:9000" -D "sonar.login=your_sonarqube_token"

This has worked for me as expected.

A: Use it like that in windows Terminal:
.\gradlew sonarqube  -Dsonar.host.url=http://my.url   -Dsonar.login=login --stacktrace
After that ,you will find the project already in the SonarQube server.


text:
Q: Applying a function to an arbitrarily long list of arguments I want to create a function apply that takes a function with an arbitrary amount of arguments as well as a list of integers, and returns the result of the function (Where each integer in the list is an argument in order.
I was thinking something like:
apply :: ([Int] -> Int) -> [Int] -> Int
apply f x:xs = apply (f x) xs
apply f [] = f

But I know this won't work because the type signature is wrong - the function doesn't take a list of ints, it just takes some amount of int arguments.
Additionally, when I get to the base case the f argument to apply should actually be an integer, violating the type signature anyway.
Does anyone know how to deal with this sort of problem?

A: You can do it with some fancy type classes
{-# LANGUAGE FlexibleInstances #-}
-- for ApplyType (Int -> r)

class ApplyType t where
    apply :: t -> [Int] -> Int

instance ApplyType Int where
    apply f _ = f

instance (ApplyType r) => ApplyType (Int -> r) where
    apply f (x:xs) = apply (f x) xs

main :: IO ()
main = do print $ apply ((+) :: Int->Int->Int) [1, 2]
          print $ apply ((\x y z w -> x*y - z`div`w) :: Int->Int->Int->Int->Int) [3,5,8,2]

A:
I want to create a function apply that takes a function with an arbitrary amount of arguments as well as a list of integers,

Why do you want to do this? Perhaps your argument structure should be passed as a data structure, but so far you've over constrained the problem to ensure it won't produce an idiomatic Haskell solution.


text:
Q: Can zsh `else` reserved keyword command be aliased and the lexem itself be repurposed as `fi` keyword command? Following ZSH: Call in-built function from zsh function that uses the same name and Run a command that is shadowed by an alias, it might be expected that a command keyword equivalent of what builtin and command are doing for their respective eponymous token category; so that
if [ -z 'love' ]; then echo 'sad world'; keyword else echo 'wonderful world'; fi

would be equivalent to
if [ -z 'love' ]; then echo 'sad world'; else echo 'wonderful world'; fi

This problem was found in the following tricky scenario: being able to replace else with alie and fi with else. See Can zsh buildtins be aliased? for more details.
So an hypothetical attempt to implement that, if the keyword command existed, would be:
alias alie="keyword else"
  alias else='fi'
So, to sum it up, the question is how do you make the following peace of zsh code works as expected by the previous command:
if [ -z 'love' ]; then echo 'sad world'; alie echo 'wonderful world'; else

A: This is not yet a working solution, but here is an idea: using the -r flag of enable and disable builtin commands to change visibility of the else keyword. So:
alias se='enable -r else; if'
alias alie='else'
disable -r else
alias else="fi; disable -r else"

This unfortunately doesn't work
se [ -z 'amo' ]; then echo 'trista mondo'; alie echo 'mirinda mondo'; else
# zsh: parse error near `fi'

This is however really on the "else" substitution that something break, as a non-inline version will indeed enter the else-branch and print "mirinda mondo".


text:
Q: missing section title in ps but not in dvi A have the document with 23 figures and 46 tables (appendix to journal article). There are 23 sections created in the exactly same manner. When viewing compiled dvi everything is in order, but after creating ps file from the dvi one of the section title is missing. Producing pdf from dvi doesn't help. What may be the problem? I can give source file if necessary.

A: Are there images near the section title that is missing?  What format are the images in?  Does removing those images fix it?

A: Thanks Alex :)
All the images in the document are eps files located just after each \section tag. The particular image had 'angle' option set to '270'. When I rotated the image in inkscape and removed 'angle' option the problem disappeared.
How can one explain such behavior?
Apparently there are two more figures with the 'angle=270', but there are no problems with that.

regards
chriss


text:
Q: Promise doesn't get resolved in route before controller got instantiated I'm trying to get the needed data directly in the route, before the controller which is going to render the view got instantiated.
For instance:
angular.module( 'mean.characters', ['ui.router', 'ui.bootstrap'] );

angular.module( 'mean.characters' ).factory('CharactersInfoFactory', ['$resource', function ($resource) {
  return $resource('/api/character/:characterId',
    { characterId: '@characterId' });
}]);

angular.module( 'mean.characters' ).config(['$stateProvider',
  function($stateProvider) {
    $stateProvider
        .state('bio', {
          url: '/:characterName/bio',
          templateUrl: 'characters/views/bio.html',
          resolve: {
                CharactersInfoFactory: 'CharactersInfoFactory',
                character: function(CharactersInfoFactory, $stateParams) {
                    var characterName = $stateParams.characterName;
                    return CharactersInfoFactory.get({characterId: characterName}).$promise;
                }
          },
          controller: 'CharactersBioController'
        });
  }
]);

angular.module( 'mean.characters' ).controller('CharactersBioController', ['$scope', 'Global', 'character',
  function($scope, Global, character) {
    $scope.global = Global;
    $scope.package = {
      name: 'characters'
    };

    $scope.character = character;

    console.log($scope.character);
  }

]);

The data is well retrieved, but the promise is not resolved before the view got rendered.
The console.log prints the info properly in console, but i also get the next error:
Error: [$injector:unpr] Unknown provider: characterProvider <- character

Besides, the view doesn't print the info ({{ character.name }} for example). It just shows the string "{{ character.name }}" instead of the name itself.
What am i doing wrong?
Thanks in advance!


text:
Q: Schottky barrier diode as a bridge rectifier? I am building a linear power supply. I need a bridge rectifier and the diodes I currently have can only handle up to a maximum of 1 amp, but I need 4-5 amps.
But I have a bunch of YG862C15R Schottky barrier diodes.
Can I somehow use them as a bridge rectifier or have I got this all wrong?
Since it only has three pins, two for the AC IN and only one for the DC OUT (I guess), won't there be any negative? Like in an IC rectifier which uses four pins. How do these work?

A: Silicon Schottky diodes have a much lower voltage drop than the standard silicon types. You can't use them on mains, because they don't make them with high breakdown voltages. In fact, they are difficult to find above 200 V. There is a manufacturing tradeoff between breakdown voltage and forward voltage drop.
In your low-voltage application you could use say 40-volt Schottky diodes, and they would waste about half the power of a standard bridge rectifier. I have used three TO220 isolated packages on battery chargers in a previous life. On larger stuff I would use four TO220 packages and four TO247 packages for special occasions.
Nowadays I bypass them with MOSFETs, because they are available with low-enough on resistance to beat the Schottky diode when the output voltage is low.

A: Yes, you can use these for a bridge rectifier 'somehow', but you will need three packages.
You can use one package for the two diodes from AC to +ve, but you will need to use two separate packages for the two AC to -ve diodes. It doesn't matter much what you do with the spare diode in the -ve packages, leave it unconnected or parallel it with the other diode.

A: In this application Schottky diodes will work just as well as normal diodes, by arranging them as you normally would a bridge rectifier. They are not normally used in regulators because they are more expensive and sometimes physically larger. The advantages of a Schottky diode (low forward voltage, fast switching) will not provide any benefit for an ordinary bridge rectifier.
The best option for hobby projects is to get a purpose made bridge rectifier that has all of your rectifier diodes integrated in one package. These cost about $2 in small quantities.
However, the specific part you have selected should not be used in a 120V bridge rectifier, because it will experience a peak-to-peak reverse voltage of 336V, well above the maximum rated 150V reverse voltage for this part. Don't do it.
And make sure you have a GFCI or isolation transformer between mains and your power supply.

A: I am surprised that the only answer that fully answered the question got the least amount of points. Awful. The question asked about how to configure a 3-pin dual diode package to create a 4 pin bridge rectifier. Using 3 of them if you only have the one polarity is correct however if you can find a 3 pin package with the opposite polarity you could make a bridge with 2 of them - that is 1 common anode and 1 common cathode. Simply connect the 2 ac pins together on both packages and the common pins become the +ve and -ve pins from the bridge. It is much simpler than using 3 packages but you might need to buy one if you don't have both polarities. Or you could use one 3 pin package and 2 discrete shottky diodes of similar specs.


text:
Q: I Could Not Find The Activation Key or activation code location/ file name If you do not provide the activation code, the website will be moved to another address. Again, if I give the activation code, then it is not going. What is the reason? Or is it possible for me to do this in a WordPress theme? But how
// Set the help sidebar
$content = __('
This is the sidebar content, HTML is allowed.
', 'redux-framework-demo');
Redux::setHelpSidebar($opt_name, $content);

Redux::setSection($opt_name, array(
    'title'            => __('Activation Theme', 'redux-framework-demo'),
    'id'               => 'purchase_theme',
    'icon'             => 'el el-home',
    'fields'           => array(
        array(
            'id'       => 'v_id',
            'type'     => 'password',
            'title'    => __('Theme Purchase code', 'redux-framework-demo'),
            'subtitle' => __('Please Active Your Theme', 'redux-framework-demo'),
            'desc' => __('For activation code Please Contect our Helpline', 'redux-framework-demo'),
            'default'  => '',
        ),
    ),
));


text:
Q: TableView sections with CollectionView and text rows how i can create TableView with three sections, but in first section I want to display CollectionView with horizontal scroll, in second section I want to display only two cells with text and in third section I want to display only three cells with text.
I have only part of code, but I think he is not correct.
class SettingsScheduleAndPricesViewController: UITableViewController {

    var dayOfWeek = [NSLocalizableMo,
                     NSLocalizableTu,
                     NSLocalizableWe,
                     NSLocalizableTh,
                     NSLocalizableFr,
                     NSLocalizableSa,
                     NSLocalizableSu]

    let sectionTitle = ["Day of week", "Second section", "Third section"]
    let secondRowText = ["First row", "Second row"]
    let thirdRowText = ["Row one", "Row two", "Row three"]

    override func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitle.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0: return 1
        case 1: return 2
        default: return 3
        }
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if indexPath.section == 0 {

        } else if indexPath.section == 1 {
            cell.textLabel?.text = secondRowText[indexPath.row]
        } else {
            cell.textLabel?.text = thirdRowText[indexPath.row]
        }
        return cell
    }
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sectionTitle[section]
    }
}
// MARK: - CollectionView
extension SettingsScheduleAndPricesViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dayOfWeek.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dayOfWeekCell", for: indexPath) as! SettingsDayOfWeekCell
        cell.dayOfWeekLabel.text = dayOfWeek[indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.bounds.width / 7.0
        let height = width
        return CGSize(width: width, height: height)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

Now I see this picture
Pls help how I can do it?

A: You can do this very easily, There are few things which are missed and misplaced in your code

*

*You haven't set height for a row in the table view.

*You need to implement your collection view's delegate and data source into the table view cell class.

*You need to define your collection view's data source into the table view's cell.

I will try to explain how you can do it with having some changes in your code.
Coding Example:
In Your View Controller:
class SettingsScheduleAndPricesViewController: UITableViewController {
    let sectionTitle = ["Day of week", "Second section", "Third section"]
    let secondRowText = ["First row", "Second row"]
    let thirdRowText = ["Row one", "Row two", "Row three"]

    override func numberOfSections(in tableView: UITableView) -> Int {
        return sectionTitle.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0: return 1
        case 1: return 2
        default: return 3
        }
    }
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
          let cell = tableView.dequeueReusableCell(withIdentifier: "DayofweekCell", for: indexPath) as! DayofweekCell
            return cell
        } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        if indexPath.section == 1 {
            cell.textLabel?.text = secondRowText[indexPath.row]
        } else {
            cell.textLabel?.text = thirdRowText[indexPath.row]
        }
        return cell
    }
}
    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.sectionTitle[section]
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    switch indexPath.section {
    case 0 :
        return //Your height
    case 1:
         return //Your height
    case 2:
         return //Your height
    default:
         return //Your height
     }
  }

}

Create One new class for DayofweekCell and setup function in it. In that class you need to add your collection view delegate and data source methods.
class DayofweekCell : UITableViewCell {

   override func awakeFromNib() {
        super.awakeFromNib()
     // Setup delegate and data source of collectionview.
    }
        var dayOfWeek = [NSLocalizableMo,
                         NSLocalizableTu,
                         NSLocalizableWe,
                         NSLocalizableTh,
                         NSLocalizableFr,
                         NSLocalizableSa,
                         NSLocalizableSu]
}

// MARK: - CollectionView Delegate and Data source methods.
extension DayofweekCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dayOfWeek.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "dayOfWeekCell", for: indexPath) as! SettingsDayOfWeekCell
        cell.dayOfWeekLabel.text = dayOfWeek[indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.bounds.width / 7.0
        let height = width
        return CGSize(width: width, height: height)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.zero
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
}

Add your collection view in your DayofweekCell and set delegate and data source there. define your data source there only. you can then use delegation to delegate your selection of collection view item to view controller. I hope this will give you an idea to solve your problem ;)


text:
Q: Calling WCF service from dynamics crm 2011 plugin I have written a plugin for Dynamics CRM 2011 that calls a WCF service hosted on a different server. Below is the code in my plugin. In the class library for the plugin I have not used a service reference but used svcutil.exe to generate a WCF client.
var binding = new BasicHttpBinding();
binding.Name = "BasicHttpBinding_IMyService";
binding.Security.Mode = BasicHttpSecurityMode.None;
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
var endpoint = new EndpointAddress("http://test/MyService.svc");
ChannelFactory<IMyService> factory = new ChannelFactory<IMyService>(binding, endpoint);
IMyService channel = factory.CreateChannel();
channel.InsertTest(testobject);

I am getting the following error:
'System.Threading.Tasks.Task`1[System.Int32]' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute.  If the type is a collection, consider marking it with the CollectionDataContractAttribute.  See the Microsoft .NET Framework documentation for other supported types.
Anyone had experience trying to do this? Or any ideas on what I am doing wrong?

A: The error your getting is with the serialization of the object you're sending.  Check to see if your testobject has a Task property.  If it does, consider ignoring it during serialization.  See this SO post.

A: *

*Make sure the service is set up correctly. I cried blood a few months ago doing that. Google for "Setting up a basic WCF web service for REST in VS 2010" and you'll probably get a hit on WordPress blog where I explain the approach. (Not trying to self-promote here. I wish someone else had that blog before I resolved the issue myself. Really.)

*Show the code that you're using to connect to the service. When I get to work tomorrow, I can compare with mine and find any difference. I remember that I had this serialization issue but I'm not sure how we killed it. But we did, somehow. (And check if Daryl's hint works. It could.)


text:
Q: Android Reading CSV Thanks in advance for the help. I want to read a CSV into array and then output contents in textView. When I run this code in the android emulator, my textView is empty. I have no idea what I'm doing wrong. The reading of the file works in normal java with print statements. Can someone tell me what the bug is here? Why the code doesn't show the string inside array[0][1] in the textView,  is it because of where I call it? I have tried all I can but can't seem to get it to work. Thanks a bunch.
package com.example.trivia;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.Button;
import android.widget.TextView;

public class PlayActivity extends Activity {
//define buttons and arrays
String [][]array;
TextView timer, questions;
Button answerA, answerB, answerC, answerD;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_play);
    initialize();

    try {
        play();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

      }

public void initialize(){
  timer = (TextView) findViewById(R.id.timer);
  questions = (TextView) findViewById(R.id.questions);
  answerA = (Button) findViewById(R.id.buttonA);
  answerB = (Button) findViewById(R.id.buttonB);
  answerC = (Button) findViewById(R.id.buttonC);
  answerD = (Button) findViewById(R.id.buttonD);
  array = new String [117][6];
       }

public void play() throws FileNotFoundException{
    String delimiter = ",";
    int row =0;
    File file = new File("questions1.csv");
    Scanner sc = new Scanner(file);

   while (sc.hasNextLine())
   {
   String line = sc.nextLine();
   String [] temp = line.split(delimiter);
   for(int i = 0; i< temp.length; i++){
      array[row][i] = temp[i];
    }
   row++;
   }
   String show = array[0][1];
   questions.setText(show);

 }
}


text:
Q: How to fix flexbox overlapping divs when using media query? I'm asking my first question here, so I apologize in advance if I didn't explain something well.
I'm currently developing portfolio website (Angular 13 with Sass). I've come to a point where I have two divs placed next to each other inside of a flexbox. I use media query (mobile view) to achieve divs to place below each other. One div contains text and other image.
I'm using Sass for flex box
@mixin flex-container($flexdirection, $justifycontent: false) {
  @if $justifycontent {
    justify-content: $justifycontent;
  } @else {
    justify-content: center;
  }
  display: flex;
  flex-wrap: wrap;
  row-gap: 20px;
  align-items: center;
  flex-direction: $flexdirection;
}

HTML component looks like this

{{title}}Andjela.

{{paragraph}}

            <button class="about__cv_button">My resume</button>

CSS looks like this
@include mq-between(xs, sm) {
  .about {
    @include flex-container(row);
    height: 100vh;
    &__img {
      background-color: aqua;
      bottom: 0;
      right: 0;
      flex-shrink: 0;
    }
    img {
      max-width: 100%;
      max-height: 100%;
    }
    &__details {
      background-color: blanchedalmond;
      left: 10%;
      right: 10%;
    }
  }
}

Result looks like in picture
I've tried using flex-direction as column, flex-basis, max-width, max-height, padding and margin, but nothing seems to make changes for what I'm looking for.
What am I missing to show the divs beneath each other with the correct height?


text:
Q: Is it possible to pause a while loop until an animation finishes? I'm trying to run a while loop that contains an animation. What I'd like to happen is for the while loop to pause, let the animation finish, then resume.
This is not my actual code, but it gets to the issue, I believe:
var counter = 0;

while (counter < 2) {

    $(".one").animate({"left":"+=50px"}, "slow", function() {

        counter++;

    });
};

This crashes my browser because it doesn't wait for the animation to finish (and consequently it doesn't wait for the counter to increase) before it continues through the while loop. Thanks in advance!
https://jsfiddle.net/uhmctey6/
EDIT
Thanks everyone for explaining why this is impossible. I'm still unsure how to do what I need, however, and since I didn't use my actual code for the example, I'm not sure if the suggested solutions could help.
Here is what I'm actually trying to do: I'm making a turing machine with a reader and a array of cells that it reads. Upon running this function, I'd like to search through a list of turing code lines to see if one matches the readers current state and the content of the current cell that the reader is scanning. If there's a match, I'd like for the reader to make a series of changes specified by the relevant turing code line, then visually move over to the next cell, and only after this animation has completed start the process over again by searching through the list of turing code lines to see if there is a match for the reader's new state, etc.
I understand that this can't be achieved as I have it, using a while loop, but is there a way to do something like this another way? Thanks a lot!
var run_program = function() {

    while (true) {

        for (var j=0; j< program.length; j++) {    //loops through the different lines of turingcode

            if (reader.state === program[j].state && reader.scanning === program[j].scanning) { //if there is a line of turingcode for the readers current state and scanning values.

                cellArray[reader.location].content = program[j].print; //change the content of the current cell to the new value

                reader.location += 1; //increase the value of the reader's location

                $(".reader").animate({"left":"+=50px"}, "slow"); //move the div to the right so it appears to be under the next cell

                reader.scanning = cellArray[reader.location].content; //update the readers scanning value to be the value of the new cell

                reader.state = program[j].next_state; // update the state of the reader to that specified by the line of turingcode

                break;

            }

            else if (j === $scope.program.length-1) { //if there is no line of turingcode for the readers current state and scanning values, and j has looped through the entire list of turingcode lines

                return;  //halt the function

            }

        }

    }

}

A: A for-loop/while-loop can run, skip and jump - but not stand still.
In other words, you cannot run asynchronous code affectively inside a synchronous loop. See this question/answer for more on that.
In the meantime, it looks like you want to run an animation a couple of times in sequence. I believe that jQuery can queue effects like animate, so it could be as simple as chaining the two calls to animate:

$(".one")
      .animate({"left":"+=50px"}, "slow")
      .animate({"left":"+=50px"}, "slow"); /* animate twice */
.one {

  position: absolute;

  width: 50px;
  height: 50px;

  background-color: green;

  left: 0;

}

Update
In response to your edit, it seems like what you want to do is turn a heavily synchronous piece of code into one that can accommodate some occasionally asynchronous behaviours.
Unfortunately, your example is unworkable for me because it has no data and context. However, I've given it a stab. Below is, untested, how I would turn your code into something as you've described in the edit of your question. I hope it helps.
var run_program = function() {

  next(0);

  // read a particular iteration
  function next (j) {

    if (j < program.length) {

      // if there is a match, stop iterating and run a method which calls next when it's finished
      if (reader.state === program[j].state && reader.scanning === program[j].scanning) {

        turing(j);

      } else {

        // if there is no turing code then next is called instantly
        next(j + 1);

      }
    }
  }

  // process a line of turing code
  function turing (j) {

    cellArray[reader.location].content = program[j].print;

    reader.location += 1;

    reader.scanning = cellArray[reader.location].content;

    reader.state = program[j].next_state;

    // may as well run this last as it is asynchronous
    $(".reader").animate({"left":"+=50px"}, "slow", function () {

      // next is called when the animation is finished
      next(j + 1);

    });
  }
}

A: This won't work for the reasons stated in the other answers. An alternative option is to use conditional recursion as such:
var counter = 0;

function myAnimation () {
  $(".one").animate({"left":"+=50px"}, "slow", function () {
    counter++;
    if (counter < 2) {
      myAnimation();
    }
  });
}


text:
Q: Visual PHP GUI IDE Does anybody know of a reliable, well-made tool for creating standalone desktop applications complete with GUI, using just PHP, or primarily PHP?  I enjoy the R.A.D. and many other aspects of PHP and would like to use it for some non server/client projects.

A: UPDATE:
The Roadsend PHP project, which I plugged in my original answer back in 2010, appears to be a dead project. For what it's worth, you can find the source and a couple of spin-off projects at:
https://github.com/weyrick/roadsend-php
For anyone looking for an answer to this question, my first suggestion would be to look into a modern cross-platform GUI development platform -- personally I like Java + Apache Pivot.
But whether you take my suggestion, or are committed to PHP-GTK, my IDE recommendation's the same: You'll want to try out NetBeans and possibly Eclipse. Both are powerful IDE's well-suited for development on either of the aforementioned platforms.
Original Answer:

Yes!
Roadsend PHP
http://www.roadsend.com/home/index.php?pageID=compiler [dead link]
http://en.wikipedia.org/wiki/Roadsend_PHP [dead link]
More information from the Roadsend site:
Build Stand Alone Applications From Standard PHP Source Code
Roadsend compiles your PHP project to a single, native binary which
  does not require an interpreter. Roadsend builds online web
  applications with FastCGI, offline web applications with an embedded
  web server (MicroServer), desktop GUI applications with PHP-GTK, and
  more! Supports Windows, Unix, and Mac OS X.
NEW: PHP 5 compatible since version 2.9.3
Roadsend Studio IDE
Roadsend Studio helps you manage, build, debug and deploy your PHP
  projects with the Roadsend Compiler. It automatically deploys a
  finished project to a directory (included supporting libraries), ready
  for packaging. It examines your code as you type, has early syntax
  error recognition, auto method and property completion and auto
  parameter help. Full syntax highlighting editor, project source file
  manager, step debugger and compiling and interpreting of projects
  (including GUI apps) from within the IDE.
Compile Web Applications
Compile web applications for both on- and offline use. Online web
  applications use the standard FastCGI interface for communicating with
  industry standard web servers such as Apache and Microsoft IIS.
  Offline web applications use the MicroServer embedded web server,
  which allows you to run an web application as a stand alone program.
Compile Desktop GUI Applications The Roadsend Compiler uses the GTK library for cross platform operability. It supports the Glade user
  interface builder and is compatible with the PHP-GTK 1 API.
Debugger
Roadsend Compiler includes a step debugger which allows you to step
  line by line through your source. You have the ability to set
  breakpoints by source file or line number, pause a running program,
  inspect local variables and inspect the call stack.
NEW: Step debug web applications!

A: There is Delphi for PHP but it appears to be fashioned for web development.

A: If you need it to run on Windows I've actually made applications for paying customers using miniPHP IDE. It's not VisualStudio for sure, but it's usable.

A: for Windows there is real cool simple but fullready thing: DevelStudio
Thats Russian, but translation included.
url: http://develstudio.ru/downloads/


text:
Q: How to bind the wrapper class data into custom objects fields and display it in pageblocktable I have created REST which fetching the data from pardot and displaying it on the vf page. It is working fine. But I need to store this data in the custom object's corresponding fields on the vf page. As of now I bind the wrapper class on the page.
Suppose, I have FirstName and LastName fields in the wrapper class which I need to store in the First_Name__c and Last_Name__c fields on the custom object from wrapper class.
Here is my REST class:
{{
       wrapper = (PardotProspectWrapper)JSON.deserialize(res.getBody(), PardotProspectWrapper.class);
      system.debug('******Wrapper*****'+wrapper); // getting response here

        //iterating wrapper response and adding to Pardot_Prospect__c object
        List<Pardot_Prospect__c> csbs = new List<Pardot_Prospect__c>();
        for (PardotProspectWrapper w : wrapper) { // Error - Loop must iterate over collection: PardotProspectWrapper
            csbs.add(w.csb);
        }
        insert csbs;
    }

//wrapper created for custom object Pardot_Prospect__c
public class PardotProspectWrapper{
public Pardot_Prospect__c csb {get;set;}
public result result{get;set;}
public class result{
    public list<prospect> prospect{get;set;}
}
public class prospect{
    public String first_name{get;set;}
    public String last_name{get;set;}

}
 }

Can somebody please tell me how can I achieve it. it would be great help.
Thank you in advance.

A: Your wrapper has a confusing structure:
public class PardotProspectWrapper {

    public class result {
        public list<prospect> prospect{get;set;}
    }

    public class prospect {
        public String first_name {get;set;}
        public String last_name {get;set;}

    }

    public Pardot_Prospect__c csb {get;set;}
    public result result {get;set;}
}

because it has a property csb that is a single record yet a property result that can represent many records. Also just a list of prospect objects would be enough to represent the data (or indeed a list of Pardot_Prospect__c).
However, using the current wrapper classes this should work:
List<Pardot_Prospect__c> csbs = new List<Pardot_Prospect__c>();
for (PardotProspectWrapper.prospect p : wrapper.result) {
    csbs.add(new Pardot_Prospect__c(
        First_Name__c = p.first_name,
        Last_Name__c = p.last_name
    ));
}
insert csbs;


text:
Q: Preventing javascript generated clicks on link
Possible Duplicate:
In Jquery, how can I tell between a programatic and user click?

Depending on the browser, there are several methods by which a link can be "clicked" using javascript.
IE (pre IE9)
element.click();
element.fireEvent('click');
Other browsers use:
element.dispatchEvent(evt) where evt is a mouseclick event.
I want to make sure that actual end user action was the originator of the event on particular links.  The technique I use now is to override these methods and filter out click events, but it is easily defeated by reverting the methods back to the prototype versions before using them.
Is there any reliable, cross browser way to determine whether or not a click event is firing as a result of direct user action (they actually clicked the element).

A: In Chrome, Firefox and Opera you can use Event.detail property, if it is not predefined by initUIEvent().
element.addEventListener('click', clickHandler, false);
function clickHandler (e) {
    if(e.detail > 0) {
        /* 1 = user click */
    } else {
        /* 0 = JS click */
    }
    return;
}

Unfortenately e.detail returns 1 in both cases in IE9 (and won't work at all in older IEs). It seems, that event properties are all exactly the same in IE (IE<9 including, 10 I don't know), despite of the source of the the click event.


text:
Q: nested model attributes + wicked wizard form not working I am making an app based on the railscast tutorial 346(Wicked gem) and 196(nested model). I am trying to combine these 2 together and I am stuck because strong param attributes are not saving.
So my app goes like this: I have a user, work, and education model.
user.rb:
has_many :educations, dependent: :destroy
has_many :works, dependent: :destroy
accepts_nested_attributes_for :educations, :works

education.rb
belongs_to :user

work.rb
belongs_to :user

And then i generated the wicked wizard controller which i called UserStepsController:
include Wicked::Wizard

steps :education, :work

def show
    @user = current_user
    @education = @user.educations.build
    @work = @user.works.build
    render_wizard
end

def update
    @user = current_user
    case step
    when :education
        @education = @user.educations.build
        @education.update_attributes(user_params)
        render_wizard @education
    when :work
        @work = @user.works.build
        @work.update_attributes(user_params)
        render_wizard @work
    end
end

strong param method:
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :password, :password_confirmation, :county_id, :area_id, :client, educations: [:school_name, :degree, :year_started, :year_finished], works: [:company_name, :work_title, :date_started, :date_finished])
end

My education and work steps view look like this:

Education

    <%= simple_form_for @user, url:wizard_path do |f| %>
    <%= f.simple_fields_for :educations do |b| %>
    <%= b.input :school_name %>
    <%= b.input :degree %>
    <%= b.input :year_started %>
    <%= b.input :year_finished %>
    <% end %>
    <%= f.button :submit, "Continue" %>
    <% end %>

Work

    <%= simple_form_for @user, url:wizard_path do |f| %>
    <%= f.simple_fields_for :works do |b| %>
    <%= b.input :company_name %>
    <%= b.input :work_title %>
    <%= b.input :date_started %>
    <%= b.input :date_finished %>
    <% end %>
    <%= f.button :submit, "Continue" %>
    <% end %>

Now, when Im in education or work step page, after clicking continue, I am getting this:
Started PATCH "/user_steps/education" for ::1 at 2015-02-26 18:03:27 +0000
Processing by UserStepsController#update as HTML
  Parameters: {"utf8"=>"V", "authenticity_token"=>"/UxsLRNrLDxEeVHLaFmRjySveLty2
UXM+x8sA058o3gdLicRGCHRSV+qBkbJtHFNtX5WXJVhEQOKFMGdKyTLhg==", "user"=>{"educatio
ns_attributes"=>{"0"=>{"school_name"=>"ssddaddsa", "degree"=>"sddssd", "year_sta
rted(1i)"=>"2015", "year_started(2i)"=>"2", "year_started(3i)"=>"26", "year_fini
shed(1i)"=>"2015", "year_finished(2i)"=>"2", "year_finished(3i)"=>"26"}}}, "comm
it"=>"Continue", "id"=>"education"}
  User Load (1.0ms)  SELECT  `users`.* FROM `users` WHERE `users`.`id` = 140 LIM
IT 1
Unpermitted parameter: educations_attributes
   (0.0ms)  BEGIN
  SQL (1.0ms)  INSERT INTO `educations` (`user_id`, `created_at`, `updated_at`)
VALUES (140, '2015-02-26 18:03:27.130368', '2015-02-26 18:03:27.130368')
   (5.0ms)  COMMIT
   (0.0ms)  BEGIN
   (1.0ms)  COMMIT

As you can see: "Unpermitted parameter: educations_attributes". The attributes school_name, degree, date_started, and date_finished are not saving into database. I already did a research how can I fix this but I am not succeeding. I don't know what to do now.
Any reponse or help will be very much appreciated. I am newbie in rails btw. Thanks.

A: When you're using accepts_nested_attributes_for you must specify your attributes to whitelist them: educations_attributes and works_attributes (as shown in the API)
def user_params
      params.require(:user).permit(
        :first_name, :last_name, :email, :password,
        :password_confirmation, :county_id, :area_id, :client,
        educations_attributes: [:school_name, :degree, :year_started, :year_finished],
        works_attributes: [:company_name, :work_title, :date_started, :date_finished]
      )
    end