text:
Q: Imitate Photoshop blend effects like multiply, overlay etc I'm making a website with a full page background image. I want to create a background image for a side column that acts like a Photoshop layer with multiply as blend mode. It's just a blue colored surface with the 'behaviour' of a Photoshop multiply layer.
It's not possible to merge the overlay and the image since the background can change when the website is opened in another screen ratio/size.

There are a lot of solutions on SO, but they only work with multiplying 2 images with a fixed position, not a colored surface with variable position/background.
Are there tricks to achieve this?

A: jsBin demo
Use the CSS3 property mix-blend-mode MDN Docs
(For fallback use an rgba or hsla color with a bit of alpha transparency.)
Assign a desired blend-* class to your element like:

/* ::: BLEND MODE CLASSES */

.blend-normal{ mix-blend-mode: normal; }
.blend-multiply{ mix-blend-mode: multiply; }
.blend-screen{ mix-blend-mode: screen; }
.blend-overlay{ mix-blend-mode: overlay; }
.blend-darken{ mix-blend-mode: darken; }
.blend-lighten{ mix-blend-mode: lighten; }
.blend-colordodge{ mix-blend-mode: color-dodge; }
.blend-colorburn{ mix-blend-mode: color-burn; }
.blend-hardlight{ mix-blend-mode: hard-light; }
.blend-softlight{ mix-blend-mode: soft-light; }
.blend-difference{ mix-blend-mode: difference; }
.blend-exclusion{ mix-blend-mode: exclusion; }
.blend-hue{ mix-blend-mode: hue; }
.blend-saturation{ mix-blend-mode: saturation; }
.blend-color{ mix-blend-mode: color; }
.blend-luminosity{ mix-blend-mode: luminosity; }

/* ::: SET HERE YOUR INITIAL COLORS */
div{
  background: rgba(0, 80, 200, 0.8);
  color:      #fff;
}
div span{
  color:#000;
}

/* ::: FOR DEMO ONLY */
html, body{margin:0; height:100%;font:100%/1 sans-serif;}
body{background: url(http://i.stack.imgur.com/cBy6q.jpg)fixed 50%/cover;}
div{font-size:2.2em; padding:20px; margin:15px;}
div:first-of-type{margin-top:150px;}
div:last-of-type{margin-bottom:150px;}

(rgba) (rgba)

normal normal

multiply multiply

screen screen

overlay overlay

darken darken

lighten lighten

color-dodge color-dodge

color-burn color-burn

hard-light hard-light

soft-light soft-light

difference difference

exclusion exclusion

hue hue

saturation saturation

color color

luminosity luminosity

A: Simple with a bit of SVG:
<svg width="200" height="200" viewBox="10 10 280 280">
    <filter id="multiply">
        <feBlend mode="multiply"/>
    </filter>
    <image id="kitten" x="0" y="0" width="300" height="300" xlink:href="http://placekitten.com/300" />
</svg>

and some CSS:
#kitten:hover {
    filter:url(#multiply);
}

The fiddle: http://jsfiddle.net/7uCQQ/

A: As FC said you can use CSS3 custom filters or SVG/Canvas.
But if you need a cross-browser solution for blending layers you have to use JS method. For example, JS image processing script from Pixastic: http://www.pixastic.com/lib/docs/actions/blend/
In addition it has a lot of other visual effects like blur, noise, crop, mosaic etc.
I used this script before for several projects, it works realy great :)
Hope it helps you)

A: I'm a designer and had the same problem, looking for solutions before putting the psd over to the dev team - you can try this js  and/or http://css-tricks.com/basics-css-blend-modes/
Jsfiddle code:
#kitten:hover {
    filter:url(#multiply);
}

<svg width="200" height="200" viewBox="10 10 280 280">
    <filter id="multiply">
        <feBlend mode="multiply"/>
    </filter>
    <image id="kitten" x="0" y="0" width="300" height="300" xlink:href="http://placekitten.com/300" />
</svg>

Hope it works for you or others here. :)


text:
Q: What is the difference between these two styles of writing functions in Javascript I am struggling to find out what is better between following two versions of Javascript fucntions
var FirstName = function(){
    var value = 0;

    this.getValue = function(){
        return value;
    }
}

and
var FirstName = function(){
    var value = 0;

    return {
        getValue: function(){
            return value;
        }
    }
}

I do understand that the latter one forms a closure but I do not understand, from usage perspective what advantage does closure in second style provide over the first one?
EDIT: Based on comment from Felix, both the functions form closure. So semantically there is no difference between these two functions (as far as I understand them). So which is a preferred way? Is there any guideline?

A: The second way seems a little redundant in this case. But I'm sure there are cases where it may be more beneficial to use the second way. I personally go with the first one just because it makes for cleaner and less confusing code usually. It's just a preference thing. Whichever you like and whichever is consistent with the rest of the code you are working on. Consistency is the most important thing.

A: The first method does not return anything but just creates the function as a global variable, whereas the second returns the inner function as a member of an object.
By returning the inner function, you can set and maintain different states of the function throughout your code, whereas with the first one, it will overwrite the method every time you run it. Seems like the latter is more flexible..
You can mess around with this demo I made.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android ROOM LIVEDATA not emitting the results Hi i have a list of items that i retrieve from a data source and then i apply a map on the observable to store the data into ROOM.
It manages to add it to the table but when i try to retrieve a LiveData of it, It doesnt seem to notify my observer of the results.
There is definetly data in the table and my query works as i changed the return time from LiveData to simple a List and that worked perfectly fine
Here is my data class
@Entity
data class Item(
        @PrimaryKey
        val id:String,
        val title: String,
        val description: String,
        val imgUrl: String,
        val  usageRules : List<String>,

)

Here is my DAO that exposes a func that add all the list of Items
@Dao
interface MyDao {

@Insert(onConflict = OnConflictStrategy.IGNORE)
    fun saveAllItems(itemList: MutableList<Item>)

       @Query("SELECT * FROM items")
    fun getAllItems(): LiveData<MutableList<Item>>

}

My DB class
@Database(entities = arrayOf(Item::class), version = 1, exportSchema = false)
@TypeConverters(UsageRulesTypeConverter::class)
abstract class MyDatabase : RoomDatabase() {
    abstract fun getProductDao(): MyDao
}

Below is how i insert data into the database:
@Inject
lateInt val database : MyDatabase

   override fun getAllItems(): Single<LiveData<MutableList<Item>>> {
     //retrieve new data using rertrofit
        networkController.getItems().map { responseItems ->
            saveAllItems(responseItems )
            getItems()
}

@Transaction
 fun saveAllItems(allItems: ItemsDataSource) {
    database.getProductDao().saveAllItems(allItems.loadedItems)
    database.getProductDao().saveAllItems(allItems.savedItems)
    database.getProductDao().saveAllItems(allItems.expiredItems)
    database.getProductDao().saveAllItems(allItems.unloadedItems)
}

fun getItems() : LiveData<MutableList<Item>>{

    return database.getProductDao().getAllItems()
}

My data source retrieved 4 lists of Items that i then save all of them in one entity/table but LiveData doesnt notify my UI about it?
ViewModel:
override fun getUnloadedOffers(): LiveData<MutableList<ProductOffer>> {
        if (!this::itemsLiveData.isInitialized) {
            itemsLiveData= MutableLiveData()
//get data from network or database
            itemDelegator.getItems()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe({ items->
                        itemsLiveData= items

                    })
        }

        return itemsLiveData
    }

UI
viewModel = ViewModelProviders.of(this, viewModelFactory).get(MyViewModel::class.java)

     viewModel.getItems().observe(this, Observer {
                items->
                items?.let {
                    adapter = SomeAdapter(items)
                    itemsRecyclerView.adapter = adapter
                    adapter.notifyDataSetChanged()
                }

            })

A: Does your function getUnloadedOffers() return empty mutableList? I'm not sure if passing items to itemsLiveData is going to work, since observing LiveData is running on bg thread (if I'm not mistaken)

A: Try to use vararg instead of List when saving collection of data.
@Insert(onConflict = OnConflictStrategy.IGNORE)
fun saveAllItems(vararg itemList: Item)

And then you can call this method using * (also known as Spread Operator) on your list like this
saveAllItems(*responseItems.toTypedArray())


text:
Q: Changing an image path in a Genesis function - from the '/images/' folder to the Media Library I'm tinkering with some code in a Genesis functions.php file, trying to figure out a way to replace the section of code below that pulls the header image as: ).
The code itself works beautifully for a full-width responsive header, but the image must be placed in the child theme's images folder and I need a way to change the image path so that it is pulled from the WordPress Dashboard > Customize > Header Image > Add New > (Media Library).
Basically I need a workaround so I can have it pull from images uploaded via the WordPress Customizer instead of placing an image directly into the images folder of the child theme.
My goal is to make it as user friendly as possible for a 'not-at-all-techy' client, so I'm trying to customize the theme to allow image changes from the dashboard/customize feature rather than FTP because they want an easy way to change the header image often, right from the dashboard.
I'm not even sure it can be done, but any ideas are greatly appreciated!
add_filter( 'genesis_seo_title', 'filter_genesis_seo_site_title', 10, 2 );
function filter_genesis_seo_site_title( $title, $inside ){
    $child_inside = sprintf( '', trailingslashit( home_url() ), esc_attr( get_bloginfo( 'name' ) ), esc_attr( get_bloginfo( 'name' ) ), esc_attr( get_bloginfo( 'name' ) ) );
    $title = str_replace( $inside, $child_inside, $title );
    return $title;
}

A: Could you set up custom header support in child theme functions.php? i.e.
add_theme_support( 'genesis-custom-header', array( 'width' => 960, 'height' => 100 ) );

The codex has more info about Custom Headers.


text:
Q: Is there a way to code the disabling of saving passwords in modern browsers (like Chrome 42)? I have a asp.net/MVC/Razor project that the client has requested not save username and passwords.  I've found multiple sites saying that autocomplete = "off" or autoCompleteType = "disable" should work, but they don't work for me in Chrome 42.  I've seen sites that say autocomplete is in HTML5 and should work, but I've also seen sites that say it is NOT supported by modern browsers.  My questions are:

*

*Can someone give me a definitive answer on whether there is a way to block saving passwords in modern browsers?  And, if there is, how to do that?

*If this can't be done, can someone point me to a website that explains that this can't be done in modern browers?  I don't want a stackoverflow comment or message board discussion; I need a definitive, clear, professional explanation that I can show to the client explaining why this can't be done in a simple way.
Here are a couple sites that seem to disagree with each other:
"IE11 dropped support for autocomplete=off for input type=password at both the form and element level."
How to disable autocomplete for a HTML password field in IE11?
"HTML5 has an autocomplete attribute which can be specified as either on or off in a field."
Autocomplete text input for HTML5?
Here is the code I've use with the autocomplete tags:
In the form:
@using (Html.BeginForm("Login", "Admin", FormMethod.Post, new { @autocomplete = "off", @autoCompleteType = "disable"}))

In the input tags:
@Html.TextBoxFor(m => m.UserName, new { @class = "span12", @autocomplete = "off", @autoCompleteType = "disable" })
@Html.PasswordFor(m => m.Password, new { @class = "span12", @autocomplete = "off", @autoCompleteType = "disable" })

I also tried enabling autocomplete through javascript:
$("input:text,form").attr("autocomplete", "off")

Also tried setting the text boxes to blanks, but the values still get populated by the browser:
$("#UserName").val("");
$("#Password").val("");

A: Thanks to @DCoder for finding this:
"TUESDAY, APRIL 8, 2014...Chrome will now offer to remember and fill password fields in the presence of autocomplete=off. This gives more power to users in spirit of the priority of constituencies, and it encourages the use of the Chrome password manager so users can have more complex passwords."
http://googlechromereleases.blogspot.com/2014/04/stable-channel-update.html
If anyone find any other official statements, please post it here.  Thanks!


text:
Q: Switch fragment Fail inside viewpager My hierarchy is like this.A viewpager included 3 pages(all fragment),called
NewFragment,InvoledFragment and MeFragment,and outside the viewpager i set a Radiobutton to switch between Newfragment and another fragment named Hotfragment,for some reason i used hide(),show()to manage the switch,here is![enter image description here is my code
Page 1
Page 2
Page 3
RadioButton check listener
private class CheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.button_new:
                mFragmentAtPos0 = newfrag;
                fragTransaction = fragmentManager.beginTransaction();
                if(!newfrag.isAdded()){
                    fragTransaction.hide(hotfrag).add(R.id.mainviewpager,newfrag).commit();
                }
                else{
                    fragTransaction.hide(hotfrag).show(newfrag).commit();
                }
                mFragmentAtPos0 = newfrag;

                Toast.makeText(MainActivity.this, "NEW", Toast.LENGTH_SHORT).show();
                break;
            case R.id.button_hot:

                fragTransaction = fragmentManager.beginTransaction();
                if(!hotfrag.isAdded()){
                    fragTransaction.hide(newfrag).add(R.id.mainviewpager,hotfrag).commit();
                }
                else{
                    fragTransaction.hide(newfrag).show(hotfrag).commit();
                }
                mFragmentAtPos0 = hotfrag;

                Toast.makeText(MainActivity.this, "HOT", Toast.LENGTH_SHORT).show();
                break;

        }
    }
}

and the FragmentPagerAdapter
private class MyPagerAdapter extends FragmentPagerAdapter {

    private final FragmentManager mFragmentManager;

    public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
        super(fm);
        mFragmentManager = fm;
    }
    @Override
    public Fragment getItem(int position) {
        if(position == 0){
            Log.d("check","111");
            return mFragmentAtPos0;
        }
        else if(position == 1){
            return(new InvolveFragment());
        }
        else {
            return(new MeFragment());
        }

    }
    @Override
    public int getCount() {
        return 3;
    }
    @Override
    public int getItemPosition(Object object)
    {
    if (object instanceof NewFragment && mFragmentAtPos0 == hotfrag)
        return POSITION_NONE;
    return POSITION_UNCHANGED;
    }
}

My problem is the HotFrag didn't show,but it worked (I put log code in hotfrag to check),and viewpager just works fine,I stucked here for several hours but still got no way to solve it.
There is a answer i found quite similar,it's here
Replace Fragment inside a ViewPager, but i worked with hide,show, not replace.
Anyone could help?Thanks a lot!


text:
Q: IInputSelectionProvider not considered by listeners of RCP SelectionService I have a RCP application with different views. The views should interact with each other through the Eclipse SelectionService.
In view 1 I have added a SelectionListener with
getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this.listener);

In view 2 I have added a SelectionProvider with
getSite().setSelectionProvider(this);

To get this working, I implemented the methods from the IInputSelectionProvider in view 2. When I run my program, view 1s selection listener is not invoked. After debugging,
I found out that view 1 is not added in the list of listeners of view 2. In view 2 I have a method
private ListenerList listenersList = new ListenerList();

@Override
public void addSelectionChangedListener(ISelectionChangedListener iselectionchangedlistener) {
  // TODO Auto-generated method stub
  listenersList.add(iselectionchangedlistener);
}

which adds listeners to the IInputSelectionProvider. My question is: Who should call this method. My understanding is that Eclipse SelectionService should does this with
getSite().getWorkbenchWindow().getSelectionService().addSelectionListener(this.listener);

But it doesn't work. Do I have to fill the listenerList by myself? If yes, why do I have to use the SelectionService at all?
Or do I have to iterate through the list of listeners by calling any other method and not using the list at all? Because if I inspect the ISelectionService object
ISelectionService service = getSite().getWorkbenchWindow().getSelectionService();
I see all the listeners.
But they are not part of the listenerList above.

A: The addSelectionChangedListener is called every time a view gets activated and removed when a view is not longer active. This means: If View A is active and 'setSeletion' is called, all views which are listening are notified. If these views by themselves call 'setSelection' nothing happens. No notification is started.


text:
Q: Zenity not dealing well with a list with multiple columns I have been trying to code a small installer script for Fedora, but when it reaches my zenity list it says This option is not available. Please see --help for all possible usages. and the std-output is 255. My code is as follows:
zenity --list --text="Choose apps to install!" --checklist --mulitple --hide-column=4 --print-column=4 --seperator=" " \
--column="Install?" --column="Name"  --column="Description" --column="Package Name"\
FALSE "Chromium" "Basically Chrome" "chromium"\
FALSE "GNOME Tweaks" "Change the font and theme" "gnome-tweaks"\
FALSE "Pitivi" "Video editing application like iMovie" "pitivi"\
FALSE "Blender" "A 3D modeling application" "blender"\
FALSE "Steam" "A platform to buy, install, and play games" "steam"

I have tried putting the numbers in strings, reordering the options, and nothing has worked. Is it just my Zenity, or is my code bad? Thanks to anyone who can help. :)

A: *

*There is a typo error: use --multiple in place of --mulitple

*Don't use contradictory options --hide-column=4 --print-column=4

*There is a typo error: use --separator in place of --seperator

*Option --separator=" " is not true against FALSE and result with mismatched columns, hence, remove this option also.

A: Answer: The seperator was making it crash It needs to be spelled separator. Silly me!


text:
Q: WakerBehaviour gets blocked by other activities I am working on a multi-agent system in JADE and use WakerBehaviours to simulate events.
However, in some cases, the WakerBehaviour wakes up much too late which leads to problems. I have tested this in the following code, but the "Im awake"-message always pops up, AFTER the while-loop is completed. how could i avoid this?
public class Test_Agent extends Agent {
protected void setup() {
    Tools.prnt(this, "starting waker");
    addBehaviour(new TickerBehaviour(this, 1000) {
        protected void onTick() {
            Tools.prnt(myAgent, "Im awake.");
        }
    });
    int i = 0;
    while(i < 100000) {
        System.out.println(i+" waiting.");
        i++;
    }
}

Thanks in advance!
Cheers, Jacek

A: As far as I know, processing of behaviours starts after setup().
that is why you should move loops inside a behaviour and If you want to handle events during loop, avoid loops and use cycle behaviour (because behaviours is processed in turn).


text:
Q: Examples of logical possibility According to Wikipedia, something is logically possible if it doesn't imply a contradiction. In that case, how could a mathematical statement be false but possible? Wouldn't a false statement be false because it contradicts a mathematical axiom, making it logically impossible? What are some examples of such statements?

A: Something may be logically possible while it is actually false.
It is possible you might have met the queen of England at a football match last Sunday.   Have you actually done so?
It is not possible you might have met the queen of England at a football match while she was actually sailing on a royal yacht.   That would be a contradiction.

Basically, something is possible if there is some alternate universe in which it can happen.   Though we usually make some restrictions on what type of alternate universe we consider; in modal logic these are known as "accessible worlds".
It is possible that the queen could go to the same football match as you do.  It's not a likely scenario, but it is possible.
It is not possible that the queen can be in two places at once; unless we consider universes where she has superpowers.

A: Here is a concrete example. Let our base system be Euclidean geometry without the parallel postulate. Then, in our ordinary understanding, the parallel postulate is true (it is true in the standard Euclidean plane) but its negation is possible (because there are other planes that satisfy the rest of the axioms of Euclidean geometry, but not the parallel postulate).
The key point is that "possible" is always with respect to some base set of axioms - the "possible" statement does not imply a contradiction from those axioms.

A: You may consider the table of truth. Consider any false sentence $P$, a sentence $Q$ and the sentence $P\to Q$. The truth table is:
$$\begin{array}[t]{c|c|c|}
P & Q & P\to Q \\
\hline
F & T & T\\
F & F & T\\  \end{array} $$
Here's an example:
Consider the axioms: "Every triangle is not a real number" and "Geometry is a field of Mathematics".

*

*If a triangle is a real number, then Geometry is a field of Mathematics.

*If a triangle is a real number, then Geometry is not a field of Mathematics.
Both of the above propositions $(P\to Q)$ are logically possible, because there is no contradiction in their content. However, the premises contradict the first axiom and for that reason they are always false. For the same reason, we can say that the second parts are true and false, respectively.
Logical possibility has nothing to do with the truthfulness or the falsity of the premises, in the sense  we don't care if the premises are true or false. We just demand no contradiction in our axiomatic system.
A contradiction in our example would be of the form:

*

*If a triangle is not a real number, then Geometry is not a field of Mathematics.

A: Mathematical truths are generally held to be necessary truths, so there shouldn't actually be any examples.
I notice that Carl Mummert's answer claims to have an example, so let me say what I think is wrong with it. The question "is the parallel postulate true?" is not a question at all until you specify the context -- are we talking about Euclidean geometry? Hyperbolic geometry? Or maybe the real world? The answers to the questions become necessarily true, necessarily false, and contingently false, in those cases respectively. (At least, according to the standard paradigm in philosophy.)


text:
Q: Modifying Objects So for my app, I have a recyclerView which holds a list of Albums (a parcelable object in my program). Each Album contains an ArrayList of Photos(another parcelable object). In my current setup, when a user taps an album a seperate activity is opened where all the photos of said Album will be displayed! Now currently i am passing my entire album to the photos activity where a user can click a button and my code access the arrayList of the album and adds a photo to it. Now when I return to my album activity, the album has not been at all modified (i.e no photos have been added). My question is whether what I am doing makes sense and modifying an object in a separate activity will change its state in the current activity!

A: Use StartAcitvityForResult() to starting new activity. In new activity make all changes in your arrayList. In when your new acitvity will finish, send result back to previous activity. Where you can update your list. Here is example of startActivityForResult


text:
Q: Fixed positioned div moves to the side while scrolling the in FireFox, works fine in other browsers I have 2 pages on my site that have the same layout. Each page has a div in the right sidebar that with the help of jquery changes it's class when you scroll down the page.
I noticed a strange behavior on one of the pages in FF.
On this page http://bit.ly/QDhrz8 when I start to scroll down, div in right sidebar shifts to the right in Firefox only. Chrome and IE works as intended.
On the other page http://bit.ly/RLZ4ZK it works as it should without shifting to right on scroll div and it works the same way without issues in FireFox, Chrome, IE.
Both of the pages use the same layout, css and java code.
What causes the div to jump on this page http://bit.ly/QDhrz8 in Firefox?

A: I cannot say why this is happening, but I found out that you can get rid of the "jumping" effect by changing this line:

to this:

I believe that the width set in the html, somehow clashes with the padding - but I can't really say that it's the true reason, but at least the fix above seems to fix your issue in FF


text:
Q: Find and print a string using a piece of other string I have the following code
    ArrayList<String> proposta = new ArrayList<String>();
    String propostaString = "";
    proposta.add("213141441414");
    proposta.add("515151551");
    proposta.add("2626262662");
    proposta.add("26262627373");
    proposta.add("7373632525");
    proposta.add("1515252");
    proposta.add("262636474");
    proposta.add("11414142222");
    String entrada = proposta.toString();

    String lastDigitsClient = "2222";
    String lastFour = "2222";
    boolean Equal = false;
    if(lastDigitsClient.contains(lastFour)) {
        Equal=true;
        System.out.println("ULTIMOS DIGITOS : TRUE = " +Equal);
        System.out.println("Lista de Propostas: " +entrada);

    }

I want to print the proposta 11414142222 using the value of lastDigitsClient, how could I do it?

A: You can use .filter() to get all values in a list that match a condition
final String lastFour = "2222";
System.out.println("Lista de Propostas: " + proposta);
Optional<String> opt = proposta.stream().filter(s -> s.endsWith(lastFour)).findFirst();
if (opt.isPresent()) {
  System.out.println("ULTIMOS DIGITOS : TRUE");
}

A: For a simple approach, I would expect something more like:
ArrayList<String> proposta = new ArrayList<String>();
proposta.add("213141441414");
proposta.add("515151551");
proposta.add("2626262662");
proposta.add("26262627373");
proposta.add("7373632525");
proposta.add("1515252");
proposta.add("262636474");
proposta.add("11414142222");

String match = "";
boolean matchFound = false;

String lastFour = "2222";
for(String s : proposta) {
  if(s.endsWith(lastFour)) {
    match = s;
    matchFound = true;
    break;
  }
}

if (matchFound) {
  System.out.println("match = " + match);
}
else {
  System.out.println("No match found.");
}

A: You can use streams API
List<String> strings = Arrays.asList(
        "213141441414",
        "515151551",
        "2626262662",
        "26262627373",
        "7373632525",
        "1515252",
        "262636474",
        "11414142222"
);
String lastFour = "2222";
strings.stream().filter(s -> s.endsWith(lastFour)).forEach(System.out::println);


text:
Q: Compare start and end time in 24 hour format without zeroes? I have two input fields, one start and one end time. They are both in 24 hour format and is displayed this way:
Start time: 01:10 End Time: 23:04 but if I inspect the input I can see that the value is really saved as this: Start time: 1:10 and End time: 23:4.
I want to compare these two times, and if they are identical, give a warning, and if the start time is greater than the end time give another warning.
This is where I am at:
$('#publish').click(function()  {
    var quantityI =  parseInt($('#time_from').val());
    var quantity = parseInt($('#time_to').val());
    /* If start time is greater then end time, show alert */
    if( quantityI > quantity) {
        $('#alert_slide_start_end_time').modal({
        });
        return false;
    }
    /* If start time and end time is identical, show alert */
    else if( quantityI = quantity) {
        $('#alert_slide_start_end_time_identical').modal({
        });
        return false;
    }
    else {
    }
});

The problem is that the compare I am doing doesn't seem to work with the format? Is it possible to convert the time into epoch and then compare it? Or what is the best approach?
EDIT: Solution here: Compare start time amd end time with jquery?


text:
Q: Webpack errors when resolving CSS urls When I use a URL in a scss file and use that file (with @import) in a Vue component, I receive the following error:
Error: Cannot find module "../images/icons/home_grey.svg"
(that path is the path relative to my scss source file). How can I stop receiving that error? My webpack.mix.js file currently includes the following lines:
mix.setResourceRoot('/root/'); mix.copyDirectory('resources/assets/images', 'public/images');

A: Maybe this is because if you are using css-loader, you need to give query param 'modules' as true. This will allow the loader to load modules.
something like this, for css-loader options,
                    options: {
                        modules: true,
                       }


text:
Q: In Lisp, why do we need to use a list function to return a list? I would have thought this would work:
(defun list-of-things (thing1 thing2 thing3)
  "returns a ???"
  '(thing1 thing2 thing3))

But this is actually what is needed to return a list:
(defun list-of-things (thing1 thing2 thing3)
  "returns a list"
  (list thing1 thing2 thing3))

A: Those are two different things, and a central concept in Lisp languages.
The syntax '(a b c) is a shorthand for (quote (a b c)) and quote is a special form that returns its argument unevaluated. In that case, it would be list, containing three symbols.
On the other hand, list is a normal function, it evaluates its arguments and return the list of their values.
To go a bit more in-depth: before evaluating any expression, the code has to be read. The part that is very specific to Lisp (and, in fact, even more so with Common Lisp) is that the "parser" is actually just a Lisp function, returning Lisp objects. Those objects are then given to the "evaluator", which evaluates them:

*

*When reading the characters '(thing1 thing2 thing3), the reader knows that ' is a reader-macro, and so it reads (quote (thing1 thing2 thing3)). This is a list of two elements, a symbol and another list of three symbols. This list is then given to the evaluator: it knows that quote is a special form that returns its argument unevaluated, and so it simply returns the list (thing1 thing2 thing3), given to it by the reader.

*On the other hand, when reading (list thing1 thing2 thing3), the reader also reads this as a list (this time, containing 4 symbols) that it then gives to the evaluator. Now, the evaluator sees that the first symbol is list, a function, and so it evaluates the arguments (i.e. it determines what the symbols thing1 ... are bound to), passes them to the list functions, etc.

All this is possible because Lisp code is defined in terms of Lisp objects (such as lists, etc). After the "parsing" (actually called reading) phase, the evaluator is really given an actual Lisp object to evaluate. Things are of course slightly more complicated when talking about compilation, etc, but the general idea is the same. The quote operator, abbreviated ', is a way to "directly" access the thing created by the reader, and to "bypass" evaluation.

A: Lisp evaluation rules
You need to understand the evaluation rules of Common Lisp first:

*

*the symbol a is a variable and evaluates to its value

*the list (operator ... ) is a form. There are four types of forms: function call, macro form, special form, lambda form

*everything else evaluates to itself: numbers, strings, arrays, hash tables, characters, CLOS objects, structures, ...

There is a fixed number of special operators. One is QUOTE. (QUOTE ...) means that the object inside does not get evaluated. '(...) is another notation for (QUOTE ...) - it's easier to write.
So symbols and lists have a role: they are variables and forms.
What if you want to have literal symbols and literal lists? Answer: you have to quote them.
Remember: If you quote a list, then the whole list including its elements is literal data and not evaluated.
Examples:
A global variable defined:
CL-USER 18 > (defvar *a* 42)
*A*

The symbol *a* is quoted and thus the form (QUOTE *A*) evaluates to the symbol:
CL-USER 19 > '*a*
*A*

Inside quoted lists everything is literal data and not evaluated.
CL-USER 20 > '(*a*)    ; same as (QUOTE (*A*))
(*A*)

The unquoted symbol is evaluated as a variable:
CL-USER 21 > *a*
42

A function call has all its arguments evaluated:
CL-USER 22 > (list *a*)
(42)

A backquote expression allows certain elements in a list to be evaluated using the comma prefix:
CL-USER 23 > `(41 ,*a* (+ 1 *a*) (+ 1 ,*a*) ,(+ 2 *a*))
(41 42 (+ 1 *A*) (+ 1 42) 44)

Summary
When you want to return a list from a function, you can:

*

*return a fixed literal list

*or compute a new list based on some objects by constructing the list with the usual operators: CONS, LIST, APPEND, ...

*or use a backquote expression which gets expanded by the Lisp reader into an implementation specific version of 2.

A: The list function is used for creating lists. They called LISP because it's for LISt Processing. Also, because Lisp functions are written as lists, they can be processed exactly like list.


text:
Q: Calculo de rendimiento "Yield" en SQL server estoy trabando con Power BI, con datos extraídos directamente de una base de datos mediante SQL sin embargo me gustaría extraer únicamente el porcentaje de piezas defectuosas de mi producto (Device_NG/Device_Total), sin embargo estos valores los extraigo de una misma columna y no se como realizar la consulta para organizar en una misma fila el calculo.
mi tabla es la siguiente:
Device_ID.......Lot_ID.........Label.................Occurrence
-----
red ................564645........device_Total.......522
red ................564645........device_NG..........68
red ................121212........device_Total.......451
red.................121212........device_NG.........32

y lo que espero es obtener lo siguiente:
Device_ID.........Lot_ID..........Scrap%
----
red....................564645........13.02
red...................121212.........7.09

gracias

A: bienvenido a StackOverflow.
Podrías agrupar los datos y condicionar la división.
DECLARE @TEST TABLE (Device_ID nvarchar(20), Lot_ID int, Label nvarchar(20), Occurrence int)

INSERT INTO @TEST VALUES ('red',564645,'device_Total',522)
INSERT INTO @TEST VALUES ('red',564645,'device_NG',68 )
INSERT INTO @TEST VALUES ('red',121212,'device_Total',451 )
INSERT INTO @TEST VALUES ('red',121212,'device_NG',32)

SELECT
     Device_ID
    ,Lot_ID
    ,SUM(CASE WHEN Label = 'device_NG' THEN Occurrence END) / CAST(NULLIF(SUM(CASE WHEN Label = 'device_Total' THEN Occurrence END),0) AS float) AS [Scrap%]
FROM @TEST
GROUP BY
     Device_ID
    ,Lot_ID


text:
Q: Find elements that appear in all given arrays I have an array of arrays:
(1, 3), (3, 5, 7), (2, 3, 4), (3, 7, 9)

I need to find a value that appears in all sub-arrays,
and in this case that number is "3".
The most efficient solution I could find was O(n^3) and I was wondering whether there is more efficient way to achieve this.

A: You can try with array_intersect:
$output = array_intersect($array1, $array2, $array3, ...);

or much automatically:
$input  = array( array(1, 3), array(3, 5, 7), array(2, 3, 4), array(3, 7, 9) );
$output = $input[0];

foreach ( $input as $key => $subarray ) {
  if ( $key == 0 ) {
    continue;
  }

  $output = array_intersect($output, $subarray);
  if ( empty($output) ) {
    break;
  }
}

var_dump($output);


text:
Q: Memory Complexity For Recursive Functions What is the memory complexity of the following function?
def remove_nodes_with_value_recursive(head,x):
  if not head:
    return
  head.next = remove_nodes_with_value_recursive(head.next, x)
  return head.next if head.val is x else head

My guess is O(n) because N recursive calls are made, so it adds those parameters N times to the stack. Is that correct? If not, please explain why.


text:
Q: If all the linear functionals are bounded, can we say the space is a Hilbert Space?

*If z is any fixed element of an inner product space $X$, show that $f(x) = \langle x,z \rangle $ defines a bounded linear functional f on X, of norm $||z||$.

*Consider Prob. 3. If the mapping $X \to X^\prime$ given by $z \mapsto f$ is surjective, show that $X$ must be a Hilbert space.
I am working on problem 4 above. I just completed problem 3 which shows the linear functional defined is bounded. Now problem 4 states the mapping is surjective which means every linear functional is of the same form so they are all bounded, but I don't see how we can conclude from this that we have a Hilbert space. Is there any relevant theorem that relates functionals to Hilbert space. The Riesz Representation theorem states that all bounded linear functional can be represented by an inner product, but I don't think it says anything about the converse.

A: You need to show that $X$ is complete. That is, any Cauchy sequence is convergent. By part 3, if $\{x_n\}\subset X$ is Cauchy, you get a corresponding sequence $\{\hat x_n\}\subset X'$. As the dual is always complete, there exists $f\in X'$ such that $\hat x_n\to f$. By the surjectivity, there exists $x\in X$ with $f=\hat x$. Now it remains to prove that $x_n\to x$.


text:
Q: how to create single ear using ant for multiple environment I have a requirement where in we have multiple properties files using which a EAR file is created for different environment like development,production etc. it takes around 45 minutes for the creation of ear in one specific environment which is a lot of time.What i want to do is create the EAR only once for all the environment and when it is deployed in the IBM WebSphere it should work.We use ant build for building the ear.
Thanks for your help

A: I think the best option would be to include a properties file in the EAR, and then adjust code in the EAR to use an env-entry to decide which properties file to use.  An administrator/developer can set the env-entry when deploying the application.


text:
Q: How do I set the 'Enable tracing' preference in an RCP application? I have an RCP application comprising of an number of plug-ins. Each plug-in contains an .options file containing trace information.
I would like to deploy the application with the Enable tracing preference set. This will enable tracing using the information defined in the option files.
How can I initially set the Enable tracing preference ?
UPDATE
I have tried following up on greg-449's answer but without success.
I created a custom.prefs file which is loaded using an entry in the product.ini file.
-Declipse.pluginCustomization=custom.prefs

custom.prefs:
org.eclipse.ui.editors/spacesForTabs=true
org.eclipse.ui.editors/tabWidth=3

org.eclipse.ui.trace/tracingEnabled=true
org.eclipse.ui.trace/tracingFilePath=atf.log
org.eclipse.ui.trace/tracingMaxFileCount=5
org.eclipse.ui.trace/tracingMaxFileSize=2000
org.eclipse.ui.trace/tracingEntries=tracingEntries=...my entries....

I added the editors prefs just as an indicator that the custom prefs were loading. When I view the editor preference page I see that the tab size is set to 3 and tabs replaced by spaces. However the tracing options remain unchanged - i.e. disabled
(I'm using Kepler and the product is based on plugins only)

A: The tracing preferences page saves the preference settings in the org.eclipse.ui.trace preferences. So they are stored in the workspace .metadata/.plugins/org.eclipse.core.runtime/.settings directory in the org.eclipse.ui.trace.prefs file.
You can set initial values for the preferences using a plugin_customization.ini file in your RCP. For example to enable preferences the entry would would be:
org.eclipse.ui.trace/tracingEnabled=true


text:
Q: How do I drop a  element onto a canvas element in HTML5? I have the following code:
<img draggable="true" id="company" ondragstart="drag_me(this, event)" src="company.jpg" />

<canvas id="canvas" ondrop="drop_here(this, event)" ondragover="return false" ondragenter="return false" width="800" height="750">

</canvas>

How do I drop the img element onto the canvas and make it appear?

A: You can't draw an element to a canvas (though an img element is the exception).


text:
Q: Proper Validation on TPageControl in Delphi I'm working with Delphi 7 code to ensure that comments are entered on a tab have been saved before users can switch tabs.
The tabs are located on a TPageControl, and this code is triggered OnExit
procedure TfCallerInfo.tsChaplainExit(Sender: TObject);
begin
  { Compare the saved DB value with the text in the comments field }
  if (dmMain.qChaplainCOMMENTS.AsString <> dbmChapComments.Text) then
    begin
      ShowMessage ('Please save the comments before proceeding.');
      pcDetail.ActivePage := tsChaplain;      // Remain on the Current Page
      tsChaplain.SetFocus;
    end;
end;

When users click on another tab tsInfoRequest for instance, the validation does trigger, but the Active Page becomes tsInfoRequest instead of remaining tsChaplain.
Any idea what I'm doing wrong?

A: There's probably a better way to do what you're trying to do. Use the TPageControl.OnPageChanging event instead.
procedure TfCallerInfo.pcDetailPageChanging(Sender: TObject;
  NewPage: TTabSheet; var AllowChange: Boolean);
begin
  if pc.ActivePage = tsChaplain then
  begin
    AllowChange := (dmMain.qChaplainCOMMENTS.AsString = dbmChapComments.Text);
    if not AllowChange then
      ShowMessage(...);
  end;
end;

By the way, a better test might be
AllowChange := not dmMain.gChaplainCOMMENTS.Modified;

TField.Modified is set to True when the content of the field is changed when it's DataSet is in dsEdit or dsInsert mode, and set to False when it's state changes back to dsBrowse.


text:
Q: Relative path for Config section file in Web.config I have several console applications and one MVC Web API application inside a folder. Is it possible for all these applications to refer to a constants.config file that resides in the parent folder?
In each of the Web.config files of all the applications, i have declared the config section as following:
<configSections>
 <section name="Constants" type="System.Configuration.NameValueFileSectionHandler, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<Constants file="~/Constants.config">

But the Constants.config is not read by the applications. How to give the path correctly?


text:
Q: Use IEnumerable variables in asp.net razor foreach loops I'm declaring my variable with this code
IEnumerable<object> Update_Select_Result= null;

and assigning with this
Update_Select_Result = DB.Query(CMD_Select, Request["UpdateID"]);

but how can I use this variable in foreach?

A: First, a type OTHER than object should be used if at all possible.  Build a specific class that mirrors your return output and wrap it in a List.
public class ReturnType
{
    public int UpdateId { get; set; }
    public string WhateverString { get; set; }
}

List<ReturnType> Update_Select_Result = null;
Update_Select_Result = DB.Query(CMD_Select, Request["UpdateID"]);

Note, you will probably have to modify your data access.  another option is to construct a new object from your return from the database.
At the top of your razor view, assign Model your new type
@model List<ReturnType>

Now that you have your model assigned, you can access it directly with "Model".  Within your razor syntax, iterate over the collection and perform whatever magic you need to.
@foreach (var x in Model)
{
    // do whatever you need with each member of Model (List<ReturnType>),
    // represented by x

}


text:
Q: React Virtualized List scrolling out of view I have a working virtual scrolling Grid for to display a document by sections on the page. I now added another RV for search results, but for some reason the contents scroll out of view when I scroll down!! I tried to simplify it to just use a List with predetermined heights and eliminate potential factors and it still gave me this strange bug. The code itself works as expected, it is the list which is acting up. (I'm actually using Cell Measurer to get row height, but even with the following version it acts up).
Here is the code:
const rowRenderer = ({ index, isScrolling, style, key  }) =>
  this.resultRowRenderer(index, key, style, curList)

resultRowRenderer(index, key, style, list) {
  ...
  return <Markup content={quote} onClick={() => jumpToLocCallback(location)} />
}

render() {
  ...
  const renderList = (curList, i) => {
    const rowCount = curList.results.length

    return (
      <List
        key={i}
        height={100}
        rowHeight={30}
        rowCount={rowCount}
        rowRenderer={rowRenderer}
        overscanRowCount={0}
        width={700}
        ref={(ref) => this.List = ref}
      />
    )
  }

  const renderLists = searchResultsLists.map(renderList)

  return (
    <div className='results-sidebar'>
      {renderLists}
    </div>
  )
}

Thanks

A:
but for some reason the contents scroll out of view when I scroll down!!

This is almost always caused by a missing style value. (See here.)
In your case, you should change this:
resultRowRenderer(index, key, style, list) {
  quote = '...'
  return <Markup content={quote} onClick={() => jumpToLocCallback(location)} />
}

To this:
resultRowRenderer(index, key, style, list) {
  quote = '...'
  return (
    <Markup
      content={quote}
      key={key}
      onClick={() => jumpToLocCallback(location)}
      style={style}
    />
  )
}

Note the added key and style attributes. ;)


text:
Q: Windows Phone Allignment of a repeating image control I am developing an application and I have an image control that displays however many images are stored in the database. So I have got the images to display. However the images are displaying below the previous one and not next to the previous one.
(ignore the names next to the picture I have taken them out now).
So my question is what method can I use to get them aligned, I'm not sure what I need to search for in Google, everything I can think of doesnt bring back anything close to what I am looking for. The XAML code is below:
 <Grid x:Name="LayoutRoot" Background="Transparent">
    <!--Pivot Control-->
    <phone:Pivot Title="Share This!">
        <!--Pivot item one-->
        <phone:PivotItem Header="All Photos">
            <Grid>
                <ListBox Height="559" HorizontalAlignment="Left" Margin="6,20,0,0" x:Name="lst_viewPhotos" VerticalAlignment="Top" Width="444" FontSize="30" ItemsSource="{Binding}" SelectionChanged="lst_viewPhotos_SelectionChanged">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal" Margin="0,10,0,0" >
                                <Image Source="{Binding}" HorizontalAlignment="Left" Height="100" Width="100"/>
                            </StackPanel>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </Grid>
        </phone:PivotItem>
    </phone:Pivot>
</Grid>

A: You can get them displaying alongside each other by setting the ItemsPanel
<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
         <VirtualizingStackPanel Orientation="Horizontal" />
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>

However I would recommend a GridView for this so that you can use a Wrapgrid which will reach the end of a Row or Column and wrap to a new Row or Column.
Something like this
<GridView>
    <GridView.ItemsPanel>
         <ItemsPanelTemplate>
             <WrapGrid Orientation="Horizontal" />
         </ItemsPanelTemplate>
     </GridView.ItemsPanel>
 </GridView>


text:
Q: oauth + php: is it possible to make code request and token request from different domains Is it possible to make code request (redirect) from one domain and then to exchange it on access token from another domain?
P.S. either domain is added on oauth provider side.
P.P.S. do every oauth provider support several domains for one app?

A: Yes, your user can start the process on one domain, and end it on another. And as soon as you have an access token, you SHOULD be free to call API endpoints from whatever machine you wish.
This is because domain has no role other than as part of your callback URL.
Basically, you are asking about the callback right? The first thing you do is not from a "domain", it is a normal HTTP request, the second a redirect to the provider, and the third is their redirect to your callback with an access token included in the URL.


text:
Q: TSQL: How to concatenate string of GROUPED values I encountered a lot of thread about this, the solutions suggested all tend to go the same way, but it is very inconvenient in my case.
Most of the time something like this is suggested.
DECLARE @Actors TABLE ( [Id] INT , [Name] VARCHAR(20) , [MovieId] INT);
DECLARE @Movie TABLE ( [Id] INT, [Name] VARCHAR(20), [FranchiseId] INT );

INSERT  INTO @Actors
    ( Id, Name, MovieId )
VALUES  ( 1, 'Sean Connery', 1 ),
    ( 2, 'Gert Fröbe', 1 ),
    ( 3, 'Honor Blackman', 1 ),
    ( 4, 'Daniel Craig', 2 ),
    ( 5, 'Judi Dench', 2 ),
    ( 2, 'Harrison Ford', 3 )

INSERT  INTO @Movie
    ( Id, Name, FranchiseId )
VALUES  ( 1, 'Goldfinger', 1 ),
    ( 2, 'Skyfall', 1 ),
    ( 3, 'Return of the Jedi', 2 )

SELECT  m.Name ,
    STUFF(( SELECT  ',' + a_c.Name
            FROM    @Actors a_c
            WHERE   a_c.MovieId = m.Id
          FOR
            XML PATH('')
          ), 1, 1, '')
FROM    @Actors a
    JOIN @Movie m ON a.MovieId = m.Id
GROUP BY m.Id ,
    m.Name

The Problem is (how shall I explain?), one does not really access the grouped Items (as Count(), Max(), Min(), ...), one does rebuild the joining pattern of the "outer query" and force in the WHERE statement, that the corresponding values are the same as those in the GROUP BY statement (in the outer query).
If you do not understand what I'm trying to say, I extended the Example above, by one additional table and you will see, that I will also have to extend the "Inner Query"
DECLARE @Actors TABLE ( [Id] INT , [Name] VARCHAR(20) , [MovieId] INT);
DECLARE @Movie TABLE ( [Id] INT, [Name] VARCHAR(20), [FranchiseId] INT );
DECLARE @Franchise TABLE ( [Id] INT , [Name] VARCHAR(20));

INSERT  INTO @Actors
    ( Id, Name, MovieId )
VALUES  ( 1, 'Sean Connery', 1 ),
    ( 2, 'Gert Fröbe', 1 ),
    ( 3, 'Honor Blackman', 1 ),
    ( 4, 'Daniel Craig', 2 ),
    ( 5, 'Judi Dench', 2 ),
    ( 2, 'Harrison Ford', 3 )

INSERT  INTO @Movie
    ( Id, Name, FranchiseId )
VALUES  ( 1, 'Goldfinger', 1 ),
    ( 2, 'Skyfall', 1 ),
    ( 3, 'Return of the Jedi', 2 )

INSERT  INTO @Franchise
    ( Id, Name )
VALUES  ( 1, 'James Bond' ),
    ( 2, 'Star Wars' )

SELECT  f.Name ,
    STUFF(( SELECT  ',' + a_c.Name
            FROM    @Actors a_c
                    JOIN @Movie m_c ON a_c.MovieId = m_c.Id
            WHERE   m_c.FranchiseId = f.Id
          FOR
            XML PATH('')
          ), 1, 1, '')
FROM    @Actors a
    JOIN @Movie m ON a.MovieId = m.Id
    JOIN @Franchise f ON m.FranchiseId = m.Id
GROUP BY f.Id ,
    f.Name

And now, going somewhat further, imagine a huge query, very complicated, several grouping values over many tables. Performance is an issue. I don't want to rebuild the whole joining pattern in the "inner query".
So is there any other way? A way that does not kill performance and you do not have to duplicate the joining pattern?

A: Contrary to what I said in this comment, you need no GROUP BY clause, nor a WHERE clause, at all!
You simply need the outer SELECT to "iterate" over all franchises (or whatever you want to group by). Then in the inner SELECT, you need some JOINs to get to the franchise key column. Instead of a WHERE clause to filter by the outer franchise's key, simply use the outer franchise key directly in the INNER JOIN:
SELECT f.Name AS FranchiseName,
       COALESCE(STUFF((SELECT DISTINCT ', ' + a.Name
                       FROM @Actor a
                       JOIN @Movie m ON a.MovieId = m.Id
                       WHERE m.FranchiseId = f.Id
                       ORDER BY ', ' + a.Name -- this is optional
                       FOR XML PATH('')), 1, 1, ''), '') AS ActorNames
FROM @Franchise f

Source of information: "High Performance T-SQL Using Window Functions" by Itzik Ben-Gak. Because SQL Server unfortunately does not have an aggregate/window function for concatenating values, the book's author recommends something like the above as the next best solution.

P.S.: I've removed my previous solution that substituted an additional JOIN for a WHERE clause; I am now fairly certain that a WHERE clause is likely to perform better. Nevertheless, I left some evidence of my previous solution (i.e. the striked-through text) because of that reference to a comment I made earlier.


text:
Q: Отображение дублированного кода имеется функции загрузки модели
   var canvas = document.querySelectorAll(".cv").forEach(el =>
   el.addEventListener('click',loadModel(), false));

    var viewer = new JSC3D.Viewer(canvas);
    var logoTimerID = 0;

function loadModel() {
    if(logoTimerID > 0) {
        clearInterval(logoTimerID);
        logoTimerID = 0;
        viewer.enableDefaultInputHandler(true);
    }
    var models = document.getElementById('model_list');
    viewer.replaceSceneFromUrl('models/' + models[models.selectedIndex].innerHTML);
    viewer.update();
}

она выводит модель без проблем, но при дублировании html-кода по выводу модели,

              <canvas  id="cv" width="1100";  height=550"></canvas>

                <select id="model_list">
                  <option>dragon.stl</option>
                </select>
                <button id="load" onclick="loadModel();">Load</button>

                    <select  id="render_mode_list" id="change" onclick="setRenderMode();">
                      <option>сглаживание</option>
                      <option>каркас</option>
                      <option>плоская</option>
                      <option>вершины</option>
                      <option>освещение OFF</option>
                    </select>

выводится только одна модель, в дублированную часть кода она отказывается загружаться(в дублированом option находится другая модель)

A: Не используйте на странице повторяющиеся id.

function loadModel(btn) {
  /* what is this timer? if(logoTimerID > 0) {
      clearInterval(logoTimerID);
      logoTimerID = 0;
      viewer.enableDefaultInputHandler(true);
  }*/
  var area = btn.closest(".Area");
  var models = area.querySelector('.model_list');
  var viewer = area.viewer;
  if (!viewer) {
    var canvas = area.querySelector('canvas');;
    viewer = new JSC3D.Viewer(canvas);
    area.viewer = viewer;
  }

  viewer.replaceSceneFromUrl('models/' + models[models.selectedIndex].innerHTML);
  viewer.update();
}

  <canvas class="cv" width="1100" height="550"></canvas>

    <select class="model_list">
      <option>dragon.stl</option>
    </select>
    <button class="load" onclick="loadModel(this);">Load</button>

    <select class="render_mode_list " id="change " onclick="setRenderMode(); ">
      <option>сглаживание</option>
      <option>каркас</option>
      <option>плоская</option>
      <option>вершины</option>
      <option>освещение OFF</option>
    </select>

пришлось столкнуться с такой ошибкой:

var canvas = document.getElementsByClassName('cv');
this.canvas.addEventListener is not a function

Вот так:
document.querySelectorAll(".cv").forEach(el =>
  el.addEventListener('click', function() { loadModel(el); }, false)
);


text:
Q: How to access all the object in the params object in Django html template? I have a function send a confirmation email template to user, the params on argument contains two object booking which is a Django object from DB and emails_text object which pulling from a json file and definitely I can access it when I print it
import json
with open('emails_text.json') as json_file:
    emails_text = json.load(json_file)

my emails_text.json file
{
  "booking_confirmation_email_template": {
  "title": "booking confirmation",
  xxxxx
}
}

but the confirmation function can read the booking object but not the emails_text
    def preview_confirmation_email(self, request, object_id, **kwargs):
        params = {
            'booking': Booking.objects.get(id=object_id),
            'emails_text': emails_text['booking_confirmation_email_template'],
        }
        return HttpResponse(content=render_email_template('email/booking/confirmation.html', params))

my confirmation.html is as follow
{% extends "email/sook_booking/temp_confirmation_base.html" %}
{% load static %}
{% load booking %}
{% block title %}Booking Confirmation{% endblock %}
xxxxxxxxx

{{emails_text.title}}

xxxxxxx


text:
Q: How could I handle a parent/child div issue with multiple dropdowns that hide and show divs? Here is the issue:

Choose Type of Request:

<select class="typeOfRequest">
    <option> Choose Type of Request</option>
    <option value="fundscenter">Funds Center Request</option>
    <option value="onlinestore">New Online Store and/or POS</option>
</select>

When "onlinestore" is selected, this dropdown pops up:

Do you need equipment?

<select id="equipmentQuestion" onchange="showDiv('hidden_div', this)">
   <option selected>Select</option>
   <option value="Yes">Yes</option>
   <option value="No">No</option>
</select>

**** This is where the issue is: When "Yes" is seleted on the above dropdown, I need this div to pop up:

Equipment Needed:

<input type="checkbox" id="ipad_checkbox"> iPad

  Qty: <input type="number" id="ipadqty" class="numberBoxes" size="35"
min="0"> </input>

<input type="checkbox" id="cct_checkbox"> Credit Card Terminal

 Qty: <input type="number" id="cctqty" class="numberBoxes" size="35" min="0"> </input>

Yet, for some reason, "hidden_div" does not show up when I make the selection "Yes."
I have a feeling that it isn't working because of a parent/child div situation, because I have scoured the internet for solutions, and all of them seem to work on their own, but not in my application. But, I wasn't sure and so I was hoping someone could lead me in the right direction:
Currently, I am using javascript, but if there is a better way, that would be fine with me too.
Here is my complete code with my HTML and JS:
https://jsfiddle.net/audgepodge626/6qomenpw/2/

A: The issue is with your markup, It's not valid when div is used as a child of table. So I just rearranged some invalid markups to make it work.

/* This function is for the yes/no dropdown for the equipment question */

function showDiv(divId, element) {
  document.getElementById(divId).style.display = element.value == "Yes" ? 'block' : 'none';
}

/* This function allows for the different types of requests to appear with select dropdown class "typeOfRequest*/

$(document).ready(function() {

  $("select.typeOfRequest").change(function() {

    $(this).find("option:selected").each(function() {

      if ($(this).attr("value") == "fundscenter") {
        $(".box").not(".fundscenter").hide();
        $(".fundscenter").show();
      } else if ($(this).attr("value") == "onlinestore") {
        $(".box").not(".onlinestore").hide();
        $(".onlinestore").show();
      } else {
        $(".box").hide();

      }
    });
  }).change();
});

/* This section deals with the checkboxes next to "Equipment Needed"*/

$(function() {
  $("#ipadqty_div").hide()
  $("#ipad_checkbox").click(function() {
    if ($(this).is(":checked")) {
      $("#ipadqty_div").show();
    } else {
      $("#ipadqty_div").hide();
    }
  });
}).change();

$(function() {
  $("#cctqty_div").hide();
  $("#cct_checkbox").click(function() {
    if ($(this).is(":checked")) {
      $("#cctqty_div").show();
    } else {
      $("#cctqty_div").hide();
    }
  });
}).change();

  <link href="style.css" rel="stylesheet">

  <link rel="icon" type="" href="../images/favicon.png">

  <link href="../css/bootstrap.css" rel="stylesheet">

  <link href="../css/metisMenu.min.css" rel="stylesheet">

  <link href="../css/sb-admin-2.css" rel="stylesheet">

  <link href="../css/font-awesome.min.css" rel="stylesheet" type="text/css">

  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

  <link href="../css/scustom.css" rel="stylesheet">

Accounting Services' Request

                            Create New Request

        <form name="form1" action="nothing.php" method="GET" enctype="multipart/form-data">

            Requester Information

              <select class="typeOfRequest">
                <option> Choose Type of Request</option>
                <option value="fundscenter">Funds Center Request</option>
                <option value="onlinestore">New Online Store and/or POS</option>

              </select>

            Contents of fundscenter box

New Online Store Request

                Name of Store:
                <input name="Requester_Name" size="30" value="<?php echo $row['FIRST_NAME'];?> <?php echo $row['LAST_NAME'];?>" required>

                Logo:
                <input type="file" name="Requester_Phone" size="10">

                Access to Reports?:

                  <select name="accesstoReports">
                    <option>Select</option>
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                  </select>

                Would you like to recieve a notification email?:

                  <select class="typeOfRequest">
                    <option> Select </option>
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                  </select>

                Notification Email Address:
                <input name="Requester_Email" size="30">

                Contact Us Email:
                <input readonly name="Requested_Date" size="15" value="<? echo $Created_Date; ?>">

                Fund Center:
                <input id="datepicker" name="Requested_Needed" size="15" required>

                GL (Not required):
                <input readonly name="Requested_Date" size="15" value="<? echo $Created_Date; ?>">

                Product excel template:

                  Template

                <input type="file" name="Requester_Phone" size="10">

                Product Images:
                <input type="file" name="Requester_Phone" size="10">

                POS:

                  <select id="posSelect">
                    <option>Select</option>
                    <option value="1">Yes</option>
                    <option value="2">No</option>
                  </select>

                Do you need equipment?:

                  <select id="equipmentQuestion" name="form_select" onchange="showDiv('hidden_div', this)">
                    <option selected>Select</option>
                    <option value="Yes">Yes</option>
                    <option value="No">No</option>
                  </select>

                Equipment Needed:

                  <input type="checkbox" id="ipad_checkbox"> iPad

                    Qty: <input type="number" id="ipadqty" class="numberBoxes" size="35" min="0" />

                  <input type="checkbox" id="cct_checkbox"> Credit Card Terminal

                    Qty: <input type="number" id="cctqty" class="numberBoxes" size="35" min="0" />

                Additional Notes:
                <textarea rows="4" cols="40"></textarea>

        </form>

FYI :
The  tag can contain the following child elements (and in this order): (Taken from here )

*

*optionally a  tag

*followed by zero or more  tags

*followed optionally by a  tag

*followed optionally by a  tag

*followed by either zero or more  tags or one or more
tags

*followed optionally by a  tag (but there can only be one
 tag child in total)

*optionally intermixed with one or more script-supporting elements
(i.e. either  tag or ) tag


text:
Q: uniform convergence of $f(\theta)=\theta, \theta \in [-\pi, \pi]$ I am mostly guessing using the theorem that because $f$ is Lipschitz continuous with $L= 2\pi$, $\sum_{n=1}^{\infty}\frac{(-1)^{n+1}\sin{n \theta}}{n}$ converges uniformly to $f$.
Is this start on the right track towards proving the uniform convergence on the interval $[-\pi,\pi]$?

A: When considering the uniform convergence of Fourier series, one must take into account the continuity of the periodic extension of $f$. This is because if a Fourier series converges uniformly on $[-\pi,\pi)$, then (by periodicity) it converges uniformly on $\mathbb{R}$; hence its sum is a continuous function on $\mathbb{R}$.
Given that $f(\theta)=\theta$  on $(-\pi,\pi)$, it is clear that the periodic extension is discontinuous at $\pi$: the limit from the left is $\pi$, the limit from the right is $-\pi$. (It may help to sketch the periodic extension.) Thus the Fourier series does not converge uniformly.


text:
Q: What is the best practice for retrieving DB2 records in an RPGLE program that originally used a multiple-format logical file? I will be rewriting an old Inventory Transaction program written in RPGLE. It's a really old program that doesn't use subfile capabilities, but writes the data to an array and has output specs specified within the program. It is all GOTO logic. In addition, it doesn't use logical conditions (If/Endif), but it has the old code where it sets indicators on/off and then the subsequent lines have the indicator identified on the left side for each operation code.
So, my question...
The current program uses a multiple format logical file, consisting of four different files: an inventory transaction file for sales orders, an inventory transaction file for purchase orders, an inventory transaction file for purchase orders, and an inventory transaction file for adjustments. The key fields are: ItemNumber, Warehouse, TransactionDate, UniqueIdentifier, TransactionType.
I'm told we should get away from this type of logic and use SQL instead, but I'm not sure what the best method would be. There are other non-common fields in each file so I don't seem to be able to use a UNION with multiple selects. The records need to be displayed in date order.
Is there a general best practice for this kind of thing?

A: UNION is the best SQL solution...
Just use CAST() or one of it's cousins to convert numeric to character when the non-common fields don't have the same type.
Additionally, if you're loading a subfile, you'd have to convert numeric to character anyway; since the subfile only supports a single record format.


text:
Q: Azure Devops pipeline trigger when a new version of helm chart is published in ACR Current my CI pipeline is building, packaging and publishing the artifacts(docker image/helm chart) to ACR.
I want to trigger my CD(continuous delivery) pipeline when either a new helm chart version/ docker image tag is published in the ACR. There are ways to do this for docker image using resources.containers.container[]. How can I put another trigger in ADO pipeline to run it when new helm chart version is published?

A: Here is a workaround:
Step 1. In your build pipeline, you can set a variable as a flag to show whether you have a new helm chart version published. And use it as a condition to set build tag. Here is an example:
- script: echo "##vso[build.addbuildtag]HelmChart"
  condition: eq(variables.varName, 'true')

Step 2. In your release pipeline, select your build as an artifact. Click on the lightening icon in your stage to set triggers:

Enable the "Artifact filters". Add your build. Fill in "build tags" with the value you set earlier in the build pipeline.
Then the pipeline will be triggered if a new helm chart version is published.


text:
Q: scrollable div on iOS doesn't scroll but just grows forever I have a simple application that has an iFrame on the main page.  In the iFrame is a scrollable div.  Events occur and are handled inside the iFrame.  The result of these events is that new lines of text are appended to the scrollable div.
Here is the code on the parent page:

And the CSS
#loggerWinR {
    position: absolute;
    top: 470px;
    left: 20px;
    width: 600px;
    height: 300px;
    padding:0.0em;
}

This is the body of the child page hosted within the iFrame:

And this is the JS (loggerR.js) that manages the child page:
function logMsg( elm, msg ) {

   elm.style.height = (window.frameElement.offsetHeight) + "px";
   var newMsg = document.createTextNode(msg);
   elm.appendChild(newMsg);
   elm.appendChild(document.createElement("br"));
   elm.scrollTop = elm.scrollHeight;
}

function handleEvent(msg) {
    logMsg( loggerRDiv, "Handler: " + " Some new stuff here");
});

This works perfectly on every platform I have tested (OSX, Windows, Android, etc.) EXCEPT iOS (8).  On iOS, instead of generating a normal scrollable div, the div (and presumably the container containing it), just gets longer and longer until it extends beyond the bottom of the page and presumably off into infinity.  It IS a scrollable div (I even tried the "momentum" CSS setting) and one can scroll the div with finger gestures.  But the div just grows and grows, letting the overflow be visible. Also tried overflow:scroll with same result.
Is this just some limitation/bug of iOS or am I missing something?


text:
Q: Most recent dated directory I have a directory which contains sub-directories in format of year/month/day.
2016/
2017/

2016/:
01/
02/
..
..

2016/01/:
01/
02/
...

...
2017/:
01/
02/
..
..

2017/01/:
01/
02/
...

...

I want to get the most recent one.. That is, this directory list wont have today's directories. I want to get the most recent one say 2017/07/19 or 2017/07/18.. whichever is the most recent one.
I am using something like DATE=(date +%Y/%m/%d) to get today's date. How to get the previous dates ?
How to get that in a bash script?

A: It may satisfy your needs.
Run it in Bash (let us suppose today is 2017/07/20 and today's directory does not exist.)
~$  (echo $(date "+%Y/%m/%d today"); find 201{6,7} -type d) | sort | grep today -B 1 | head -n 1
2017/07/19

Even 2017/07/20 directory exists, it works.
~$  (echo $(date "+%Y/%m/%d today"); find 201{6,7} -type d) | sort | grep today -B 1 | head -n 1
2017/07/20


text:
Q: Google Calendar Event Creation send Notifications I was wondering if anyone knew how to notifiy attendees upon event creation in google calendar. When I create the event manualy, I can send an event as I wish. But when I create the event using the api with the javascript client library. I do not receive email notifications.
Here is my code for creation :
var request = gapi.client.calendar.events.insert({
    'calendarId': '***@***.com',
    'resource': resource
});
request.execute(function() {
});

My resource variable is already defined and the event is added successfuly to the calendar, but no attendees receive any invitations. And if I go into the event on the calendar after creating it, the attendees are there.
Is there anything I am missing in the request to make it so that the attendees receive notifications upon the creation.

A: The attendees array has a responseStatus that you can set to:
"needsAction" - The attendee has not responded to the invitation.
"declined" - The attendee has declined the invitation.
"tentative" - The attendee has tentatively accepted the invitation.
"accepted" - The attendee has accepted the invitation.
var request = gapi.client.calendar.events.insert({
  'calendarId': '***@***.com',
  'resource': resource,
  'attendees': [{'email':'example@example.com','responseStatus':'needsAction'}]
  }
});
request.execute(function() {
});

A: You have to set parameter "sendNotifications" to true.
Here you can see that this is set to false at default.
https://developers.google.com/google-apps/calendar/v3/reference/events/insert

A: In the Java client there's the insert method of the event, and then there's the setSendNotifications method.
You'll have to do something like this:
Event createdEvent = calendario.events().insert("some-mail-from-google0@group.calendar.google.com", event).setSendNotifications(true).execute();

A: On the iOS version of the API, the sendNotifications property is on the request object - so you need to create the request first, then set the sendNotifications property before executing it. Look at the request object, see if the Java API is similar (likely).
e.g.
request.sendNotifications = true;
before calling
request.execute()

A: Adding sendUpdates : 'all' in the parameter section will solve this issue.
I am using node js library googleapis, initially i have tried with the following code
const eventDetails = {
    summary: 'Meeting with ' + bookedProject.client_name,
    description: newMeeting.message,
    start: {
        dateTime: newMeeting.meeting_date,
    },
    end: {
        dateTime: moment.utc(newMeeting.meeting_date).add(15, 'minute'),
    },
    sendUpdates : 'all',
    attendees: [{ email: bookedProject.client_email ,responseStatus:'needsAction'}],
};

But adding sendUpdates : all in options solved the problem like the below
const { google } = require('googleapis');
google.options({
    params: {
        sendUpdates: 'all'
    }
});


text:
Q: Modest sized DB with 320 second SELECT I noticed that one of my Hibernate JPA SELECTs against my Heroku PG 10.4 instance is taking a  loooog time to complete as this EXPLAIN (ANALYZE, BUFFERS) shows. The database is 591MB running in PG 10.4 on Heroku with the following row counts and index use:
    relname     | percent_of_times_index_used | rows_in_table
----------------+-----------------------------+---------------
fm_order       | 99                          |       2233237
fm_grant       | Insufficient data           |        204282
fm_trader      | 5                           |         89037
fm_capital     | 99                          |         84267
fm_session     | 99                          |          7182
fm_person      | 99                          |          4365
fm_allocation  | 96                          |          4286
fm_approval    | Insufficient data           |           920
fm_market      | 97                          |           583
fm_account     | 93                          |           451
fm_marketplace | 22                          |           275

and the offending JPA JPQL is:
@Query("SELECT o FROM Order o WHERE                                "
     + "       o.type                  = 'LIMIT'                   "
     + "   AND o.session.original      = :originalSessionId        "
     + "   AND ( (                                                 "
     + "         o.consumer IS NULL                                "
     + "    ) OR (                                                 "
     + "         o.consumer IS NOT NULL                            "
     + "     AND o.consumer > 0                                    "
     + "     AND EXISTS (                                          "
     + "       SELECT 1 FROM Order oo WHERE                        "
     + "             oo.id                    = o.consumer         "
     + "         AND oo.session.original      = :originalSessionId "
     + "         AND oo.type                  = 'LIMIT'            "
     + "         AND oo.owner                != o.owner            "
     + "     )                                                     "
     + "   )                                                       "
     + " )                                                         "
     + " ORDER BY o.lastModifiedDate DESC                          ")

which Hibernate turns into:
SELECT order0_.id                 AS id1_7_,
       order0_.created_by         AS created_2_7_,
       order0_.created_date       AS created_3_7_,
       order0_.last_modified_by   AS last_mod4_7_,
       order0_.last_modified_date AS last_mod5_7_,
       order0_.consumer           AS consumer6_7_,
       order0_.market_id          AS market_14_7_,
       order0_.original           AS original7_7_,
       order0_.owner_id           AS owner_i15_7_,
       order0_.owner_target       AS owner_ta8_7_,
       order0_.price              AS price9_7_,
       order0_.session_id         AS session16_7_,
       order0_.side               AS side10_7_,
       order0_.supplier           AS supplie11_7_,
       order0_.type               AS type12_7_,
       order0_.units              AS units13_7_
FROM   fm_order order0_
       CROSS JOIN fm_session session1_
WHERE  order0_.session_id = session1_.id
       AND order0_.type = 'LIMIT'
       AND session1_.original = 7569
       AND ( order0_.consumer IS NULL
              OR ( order0_.consumer IS NOT NULL )
                 AND order0_.consumer > 0
                 AND ( EXISTS (SELECT 1
                               FROM   fm_order order2_
                                      CROSS JOIN fm_session session3_
                               WHERE  order2_.session_id = session3_.id
                                      AND order2_.id = order0_.consumer
                                      AND session3_.original = 7569
                                      AND order2_.type = 'LIMIT'
                                      AND
                     order2_.owner_id <> order0_.owner_id) ) )
ORDER  BY order0_.last_modified_date DESC;

Any ideas how I turn this 320S disaster around?

A: Statistics were not up-to-date; executed ANALYZE and dropped the redundant:
 + "         o.consumer IS NOT NULL               "

which improved performance 100x.


text:
Q: Ruby on Rails Devise not sending email confirmation, Mailer I hope all is well. I have been trying to set up email confirmation for the past 3 days, I cant make it work. This doesnt send email. Any idea what I'm missing? thank you tons!
Btw I tried both Gmail and Sendgrid. Either of them was able to send email.

user.rb
  devise :database_authenticatable, :confirmable, :registerable, :recoverable, :rememberable, :trackable, :validatable

devise.rb
config.mailer_sender = 'myemail@gmail.com'
config.mailer = 'Devise::Mailer'
config.reconfirmable = false

development.rb
  # Email
  config.action_mailer.raise_delivery_errors = false
  config.action_mailer.perform_caching = false
  config.action_mailer.default_url_options = { :host => 'localhost:3000' }
  config.action_mailer.delivery_method = :smtp
  ActionMailer::Base.smtp_settings = {
    :address              => "smtp.gmail.com",
    :port                 => 587,
    :domain               => "gmail.com",
    :user_name            => "myemail@gmail.com",
    :password             => "mypassword",
    :authentication       => "plain",
    :ssl                  => true,
    :tsl                  => true,
    :enable_starttls_auto => true
  }

schema.rb
  create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string "unconfirmed_email"
    ....


text:
Q: Gingerbread devices not using Holo style from Theme.AppCompat (support library) I'm using the v4 and v7 support library to integrate the action bar and navigation drawer in my app, which supports API 10+.
I've followed the guide on the developer site to use Theme.AppCompat and style/Widget.AppCompat.ActionBar as the parent of my theme and action bar style, respectively.
Everything works fine, except when I test on Gingerbread devices, things like a dropdown/popup menu has a white background (skin from the phone) and text fields don't use the holo-style backgrounds (again, uses the phone skin).
Is there anything extra I need to do so pre-Holo devices inherit the holo-style widgets?
Thanks in advance.

A: Regardless of using the support library, widgets such as TextView, Spinner, CheckBox, Button, Switch etc. will not look Holo styled automatically.
What the support library lets you do is use some profoundly important UI elements and APIs that are not available on versions of Android before Honeycomb (like the ActionBar), but the style of the widgets will remain distinctly the same as it is for the API level the phone is actually running.
You have a few options here:
1.) Scavenge resources from one of the API >= 14 platforms/ subdirectories of your android SDK installation and copy/adjust the drawables and styles for the widgets you want to change yourself. However this is something I don't recommend at all, because it will be a long and arduous task if you are using many different widgets that need this kind of adjustment.
2.) Use Android Holo Colors, which is an online generator for Holo compliant resources and supports almost all of the widgets right away: http://android-holo-colors.com/
Just pick your preferred color, the API version you want to support and the widgets you want to adapt to Holo. Holo Colors will generate an archive containing all the drawables and style definitions for you. The drawables you can pretty much copy into your project straight away, the styles you'll probably have to integrate into your existing styles.xml
3.) There is a library, called HoloEverywhere (https://github.com/Prototik/HoloEverywhere), which already has most widgets adapted to Holo, but you'll need to extend their custom activity class and directly reference their adapted widgets classes.
Hope this helps!


text:
Q: How to make certain sections of my word doc stand out and look different such as by adding a different background color to the pages of the section? I have a document with 5 sections A, B, C, D, E.
I want to highlight C and E to have light grey background color. How can I do this?
Some suggestions I read on superuser for similar but not same questions mentioned separating out the documents, managing page numbers and then aggregating into a single pdf file. However, is there any other method?
Thanks.

A: Access the headers of the section and insert a large shape that covers the entire page.
Inserting a shape:

Two section, the first has a blue shape in the header. The second one doesn't


text:
Q: Does Xcode have a region feature like in the Microsoft Visual Studio? Does xcode have a region feature like in microsoft visual studio? If It has how can i create it?

A: Code folding ribbon" option in Xcode->Preferences->Text Editing needs to be selected. the follow this picture:

Or you can directly fold the code when you click on open parenthesis "{" with command then you will get option to fold the code:


text:
Q: How to extend ImageCases? I was very excited to see ImageCases being documented in version 12. But I immediately desired a mechanism for adding more entities to ImageCases, especially given that we can create our own custom entities now.
Assuming you have many images containing a new object class and you want to detect them and their ImageBoundingBoxes, is there any undocumented method or 3rd party service to achieve this?
I'm thinking that there might be a way to combine Classify with the new Image Pyramid functionality and/or ImageCases's internal feature network and do some transfer learning.


text:
Q: Using outer query result in a subquery in postgresql I have two tables points and contacts and I'm trying to get the average points.score per contact grouped on a monthly basis.  Note that points and contacts aren't related, I just want the sum of points created in a month divided by the number of contacts that existed in that month.
So, I need to sum points grouped by the created_at month, and I need to take the count of contacts FOR THAT MONTH ONLY.  It's that last part that's tricking me up.  I'm not sure how I can use a column from an outer query in the subquery.  I tried something like this:
SELECT SUM(score) AS points_sum,
  EXTRACT(month FROM created_at) AS month,
  date_trunc('MONTH', created_at) + INTERVAL '1 month' AS next_month,
  (SELECT COUNT(id) FROM contacts WHERE contacts.created_at <= next_month) as contact_count
FROM points
GROUP BY month, next_month
ORDER BY month

So, I'm extracting the actual month that my points are being summed, and at the same time, getting the beginning of the next_month so that I can say "Get me the count of contacts where their created at is < next_month"
But it complains that column next_month doesn't exist  This is understandable as the subquery knows nothing about the outer query.  Qualifying with points.next_month doesn't work either.
So can someone point me in the right direction of how to achieve this?
Tables:
Points
score | created_at
10    | "2011-11-15 21:44:00.363423"
11    | "2011-10-15 21:44:00.69667"
12    | "2011-09-15 21:44:00.773289"
13    | "2011-08-15 21:44:00.848838"
14    | "2011-07-15 21:44:00.924152"

Contacts
id | created_at
6  | "2011-07-15 21:43:17.534777"
5  | "2011-08-15 21:43:17.520828"
4  | "2011-09-15 21:43:17.506452"
3  | "2011-10-15 21:43:17.491848"
1  | "2011-11-15 21:42:54.759225"

sum, month and next_month (without the subselect)
sum | month | next_month
14  | 7     | "2011-08-01 00:00:00"
13  | 8     | "2011-09-01 00:00:00"
12  | 9     | "2011-10-01 00:00:00"
11  | 10    | "2011-11-01 00:00:00"
10  | 11    | "2011-12-01 00:00:00"

A: Edit
Now with running sum of contacts. My first draft used new contacts per month, which is obviously not what OP wants.
WITH c AS (
    SELECT created_at
          ,count(id) OVER (order BY created_at) AS ct
    FROM   contacts
    ), p AS (
    SELECT date_trunc('month', created_at) AS month
          ,sum(score) AS points_sum
    FROM   points
    GROUP  BY 1
    )
SELECT p.month
      ,EXTRACT(month FROM p.month) AS month_nr
      ,p.points_sum
      ,( SELECT c.ct
         FROM   c
         WHERE  c.created_at < (p.month + interval '1 month')
         ORDER  BY c.created_at DESC
         LIMIT  1) AS contacts
FROM   p
ORDER  BY 1

*

*This works for any number of months across the years.

*Assumes that no month is missing in the table points. If you want all months, including missing ones in points, generate a list of months with generate_series() and LEFT JOIN to it.

*Build a running sum in a CTE with a window function.

*Both CTE are not strictly necessary - for performance and simplification only.

*Get contacts_count in a subselect.

Your original form of the query could work like this:
SELECT month
      ,EXTRACT(month FROM month) AS month_nr
      ,points_sum
      ,(SELECT count(*)
        FROM   contacts c
        WHERE  c.created_at < (p.month + interval '1 month')) AS contact_count
FROM   (
    SELECT date_trunc('MONTH', created_at) AS month
          ,sum(score) AS points_sum
    FROM   points p
    GROUP  BY 1
    ) p
ORDER  BY 1

The fix for the immediate cause of your error is to put the aggregate into a subquery. You were mixing levels in a way that is impossible.
I expect my variant to be slightly faster with big tables. Not sure about smaller tables. Would be great if you'd report back with test results.
Plus a minor fix: < instead of <=.


text:
Q: Realtek wireless adapter not detected I have a tablet come PC laptop i have installed Ubuntu 16.10 , i experience a strange behavior when i boot the system Wireless adapter is not detected but i suspend the system a few times it detects the wireless card and connect and work fine but sometime  also just got disconnected while working
I tried many solutions none seems to work for me
here is the output of iwconfig command when it is connected
lo        no wireless extensions.

wlx7cc709cb1699  IEEE 802.11  ESSID:"DIY"
          Mode:Managed  Frequency:2.412 GHz  Access Point: 2C:E4:12:4E:A3:53
          Bit Rate=1 Mb/s   Tx-Power=20 dBm
          Retry short limit:7   RTS thr=2347 B   Fragment thr:off
          Power Management:off
          Link Quality=66/70  Signal level=-44 dBm
          Rx invalid nwid:0  Rx invalid crypt:0  Rx invalid frag:0
          Tx excessive retries:0  Invalid misc:34   Missed beacon:0

when it does not works
wlx7cc709cb1699  IEEE 802.11  ESSID:off/any
          Mode:Managed  Access Point: Not-Associated   Tx-Power=20 dBm
          Retry short limit:7   RTS thr=2347 B   Fragment thr:off
          Power Management:off

kindly guide what is goging wrong i also compiled two driver
rtl8723au
rtl8723bu

but problem remain the same
kindly help.

A: Finally i solved the problem by running the following commands in the following order
sudo modprobe -r rtl8xxxu
sudo modprobe 8723bu
sudo modprobe -r 8723bu
sudo modprobe 8723bu
sudo /etc/init.d/network-manager restart
sudo /etc/init.d/network-manager restart

*

*The first command removes the default module loaded for the Network Card by the kernel.

*The second command loaded the right driver "8723bu" which we compiled earlier.

The rest of the command sequence is necessary to make the network manager detect the network card successfully, Once loaded it will work fine and never disconnect while working, however you have to repeat this process on every system boot.


text:
Q: Whitelisting an unsigned kext in macOS Catalina I've recently bought an old Alesis io26 Firewire Audio interface. The last driver release was only working on mountain Lion and older. After some time I've managed to install said drivers on Catalina, by manually dragging the midi driver into /Library/Audio/MIDI drivers and installing the kernel extension into /System/Library/Extensions via KEXT droplet. The problem I have now is that my mbpro only recognises the Interface if my SIP is disabled. I've heard that the driver is not signed and that this is the reason why the SIP is preventing it from working. So as a total noob, how can I somehow whitelist that kext so that I don't have to go to recovery mode and disable SIP every time I want to record some Audio.

A: The 3 "correct" ways of doing this are probably unlikely:

*

*Get the original developer to sign the kext

*Somehow persuade Apple to add it to macOS's built-in whitelist

*If you have a kext signing certificate yourself, you can sign it. (Apparently, Apple no longer issues these, however.)

The best you can do in practice is probably to only disable the kext signing part of SIP by using the command
csrutil enable --without kext

instead of
csrutil disable

Of course, this leaves your system open to being attacked via unsigned kexts, though I've not heard of any malware that specifically targets Macs with kext signing disabled.

A: Actually, the question is for Catalina. We cannot partially disable SIP by running with --without kext. from Mojave this option is disabled and one has to either enable or disable it from Recovery OS.


text:
Q: How do I view the SwaggerUi when using Azure API Management I have an API in Azure with address;
http://webapiapplicationXXXXXXX.azurewebsites.net
and the Swagger UI at
http://webapiapplicationXXXXXXX.azurewebsites.net/swagger/ui/index
Putting this into the Azure API Management gives me an address of:
http://xxxxxxxxxxxx.azure-api.net/Time/api/TimeZoneInfo
I want to see the SwaggerUI.  I've tried the obvious URLs but got:

{ "statusCode": 404, "message": "Resource not found" }

What is the URL to see the SwaggerUI when the API is hosted in Azure API Management?

A: Usually people don't use the Swagger UI anymore once an API is behind API Management.  The reason being that the developer portal provides the equivalent and better functionality.
If you really do want to expose the underlying SwaggerUI then you can create an additional operation in API Management that points to the SwaggerUI.  The reason you are getting 404 is because API Management is saying that you are trying to access a resource that is not defined as an API Management operation.
You should be able to create the API operation like this


text:
Q: Python - Counting Letter Frequency in a String I want to write my each string's letter frequencies. My inputs and expected outputs are like this.
"aaaa" -> "a4"
"abb" -> "a1b2"
"abbb cc a" -> "a1b3 c2 a1"
"bbbaaacddddee" -> "b3a3c1d4e2"
"a   b" -> "a1 b1"

I found this solution but it gives the frequencies in random order. How can I do this?

A: Does this satisfy your needs?
from itertools import groupby
s = "bbbaaac ddddee aa"

groups = groupby(s)
result = [(label, sum(1 for _ in group)) for label, group in groups]
res1 = "".join("{}{}".format(label, count) for label, count in result)
# 'b3a3c1 1d4e2 1a2'

# spaces just as spaces, do not include their count
import re
re.sub(' [0-9]+', ' ', res1)
'b3a3c1 d4e2 a2'

A: For me, it is a little bit trickier that it looks at first. For example, it does look that "bbbaaacddddee" -> "b3a3c1d4e2" needs the count results to be outputted in the order of appearance in the passed string:
import re

def unique_elements(t):
    l = []
    for w in t:
        if w not in l:
            l.append(w)
    return l

def splitter(s):
    res = []
    tokens = re.split("[ ]+", s)
    for token in tokens:
        s1 = unique_elements(token) # or s1 = sorted(set(token))
        this_count = "".join([k + str(v) for k, v in list(zip(s1, [token.count(x) for x in s1]))])
        res.append(this_count)
    return " ".join(res)

print(splitter("aaaa"))
print(splitter("abb"))
print(splitter("abbb cc a"))
print(splitter("bbbaaacddddee"))
print(splitter("a   b"))

OUTPUT
a4
a1b2
a1b3 c2 a1
b3a3c1d4e2
a1 b1

If the order of appearance is not a real deal, you can disregard the unique_elements function and simply substitute something like s1 = sorted(set(token)) within splitter, as indicated in the comment.

A:
here is you answer

test_str = "here is your answer"
res = {}
list=[]
list=test_str.split()
# print(list)
for a in list:
    res={}
    for keys in a:
        res[keys] = res.get(keys, 0) + 1
    for key,value in res.items():
        print(f"{key}{value}",end="")
    print(end=" ")

A: There is no need to iterate every character in every word.
This is an alternate solution. (If you don't want to use itertools, that looked pretty tidy.)
def word_stats(data: str=""):
    all = []
    for word in data.split(" "):
        res = []
        while len(word)>0:
            res.append(word[:1] + str(word.count(word[:1])))
            word = word.replace(word[:1],"")
        res.sort()
        all.append("".join(res))
    return " ".join(all)

print(word_stats("asjssjbjbbhsiaiic ifiaficjxzjooro qoprlllkskrmsnm mmvvllvlxjxj jfnnfcncnnccnncsllsdfi"))
print(word_stats("abbb cc a"))
print(word_stats("bbbaaacddddee"))

This would output:
c5d1f3i1j1l2n7s2
a1b3 c2 a1
a3b3c1d4e2


text:
Q: recommended librairies for a dynamic data-driven website First I know this might be received as an opinion-based question. If it is the case, could you advise some other appropriate places to get some feedback.
I want to make a web app that renders graphically tree data structure that needs to be updated on the browser as the data changes in real time on the server, and as we navigate through the data on the client-side (like if we were moving through a 2D map in a game, getting data as we progress and as it changes)..
I can do MongoDB, nodejs, and react at the moment. I'm planning to have a deeper look graphQL based on a guess that it might be helpful. Other than that I don't have too many ideas regarding open connections (is there anything other than socket.io that I should look into?)
About the GUI, I did a bit of canvas, a while ago, but I really don't know in which directions to look to see what exists today, and even if it is worth getting refreshed in python for example..
Any feedbacks appreciated before the question is deleted..


text:
Q: Laplace transform calculation Please can someone help me? I have tried to find the Laplace transform of the form:
$$\int_{0}^{+\infty} (v+1)^{\nu}(2v+1)^{k}v^{\alpha} \exp(-pv), \mbox{ where }\alpha,\nu, k \mbox{ are integers }$$
I have searched on the two Books "Erdelyi. Tables of integral transforms, Vol I, 1954" and "Oberhettinger, L. Badii, Tables of Laplace transforms, 1973. But i didn't found this type of integral transform is there any reference or  method in order to compute this formula above.
Thanks and best regards.

A: For $n,k\in\mathbb{N}$ and $\alpha\geq 0$ we can use the binomial expansion,
$$(v+1)^{\nu}(2v+1)^{k}v^{\alpha}=\sum_{s=0}^{\nu+k}\sum_{q=0}^{s}{{\nu}\choose{q}} {{k}\choose{s-q}}2^{s-q}v^{s+\alpha} $$
$$\Rightarrow \int_{0}^{\infty} (v+1)^{\nu}(2v+1)^{k}v^{\alpha} e^{-pv}\,dv=\sum_{s=0}^{\nu+k}\sum_{q=0}^{s}{{\nu}\choose{q}} {{k}\choose{s-q}}2^{s-q}\frac{(s+\alpha)!}{p^{s+\alpha+1}}$$
$$\qquad=\sum_{s=0}^{\nu+k}2^s \binom{k}{s} \, _2F_1\left(-\nu,-s;k-s+1;\tfrac{1}{2}\right)\frac{(s+\alpha)!}{p^{s+\alpha+1}}.$$

A: Another way to look at this integral is by considering $$F(q,r,p) = \int_{0}^{\infty}\exp\left[-q(v+1)-r(2v+1)-pv\right]\,dv = \frac{\exp(-q-r)}{p+q+2r}$$ for $p+q+2r>0$. If $\nu\geq 0$, $k\geq 0$, and $\alpha\geq 0$, then your integral can be represented as
$$(-1)^{\nu+k+\alpha}\left.\frac{\partial^{\nu+k+\alpha}F}{\partial q^{\nu}\,\partial r^{k}\,\partial p^{\alpha}}\right|_{q\,=\,r\,=\,0}.$$
For negative values of $\nu$ or $k$, integration should be used instead of differentiation.
Of course, it depends on what you're looking for, so this method may not give anything better than the previous answer.


text:
Q: Using a series to approximate an inverse. Hi I was looking at a quick way to remember converting farenheit to centigrade. It's easy to remember subtract or add 32 but then you have to multiply or divide by 1.8. I approximated this to 2. On looking at the error I saw if I added the multiplication  or division  by .2 it was very close to the correct answer. So I started playing with approximations of 1/(a+b). I got 1/a - b/(a^2+ab). If you do the same approximation on the last term a series starts to appear. I remember vaguely from school that was a polynomial series. I Googled Lagrange and a few others but could not find it.
Does anyone remember the approximation of 1/(x+a) as 1/x + b/x^n .....
Thanks

A: The approximation of $\displaystyle \frac{1}{x+a}=\frac{\frac{1}{a}}{1-(-\frac{x}{a})}=\frac{1}{a}\left(1-\frac{x}{a}+\frac{x^2}{a^2}-\frac{x^3}{a^3}...
\right)$