text:
Q: WPF style for buttons I haven't used WPF for a very long time (close to 4 years). But now started to use it again for some usage, you can see one of my top asked questions is in WPF. The reason I mention is this because I do have some knowledge about WPF and how it works. My latest project invovlves using BLEND to achieve a very good UI.
So here I have a Photoshop layout, and I am trying to get this layout design,

And so far I only have this,

So really would appreciate if someone could point me on the following things.
How to get the border glow effect and curves also how to group them to a particular style in a separate file and link it to the buttons. Thanks for your time and answers
EDIT: With my styles code.
I have the following styles code in Custom_Styles.xaml (Resource dictionary)
How do I link it to the button?
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:local="clr-namespace:Keyboard_actual">

    <Style x:Key="Button" TargetType="Button">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border>
                        <Rectangle Margin="2" Stroke="#60000000" StrokeThickness="1" StrokeDashArray="1 2"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

A: For the border glow effect, you can add a Drop Shadow Effect with a Shadow Depth of 0 and the desired color and a border brush of white for the Button.
To create the style in a separate file, you need to create a Resource Dictionary like this:
Project ► Add New Item... ► Resource Dictionary
Then name your file. In this example, I name it Styles.xaml.
Now open up your App.xaml and put this within the Application tag:
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
        <!--Put all previous resources in the App.xaml here-->
    </ResourceDictionary>
</Application.Resources>

Now in the Styles.xaml file within the ResourceDictionary tag, put the style. I am working on a style too. Once I finish it I will post it.
To link the style, use:
<Button Style="{StaticResource Button}" .../>

It may not work since the key is "Button". If it doesn't change it to something like "ButtonStyle".
And the Drop Shadow Effect does a pretty decent job.
Here's an example (Zoomed at 200%):

and the XAML style:
<Style x:Key="ButtonStyle" TargetType="Button">
    <Setter Property="BorderBrush">
        <Setter.Value>
            <SolidColorBrush Color="#FF00C3BA"/>
        </Setter.Value>
    </Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="0.8" CornerRadius="3">
                    <Border.Effect>
                        <DropShadowEffect Color="#FF72FFE5" ShadowDepth="0"/>
                    </Border.Effect>
                    <TextBlock Foreground="{TemplateBinding BorderBrush}" Text="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

used like this:
<Grid Background="#FF171717">
    <Button Content="Q" HorizontalAlignment="Left" Height="47" Margin="103,59,0,0" VerticalAlignment="Top" Width="50" FontSize="20" FontFamily="Segoe UI Light" Style="{StaticResource ButtonStyle}"/>
    <Button Content="Y" HorizontalAlignment="Left" Height="47" Margin="378,59,0,0" VerticalAlignment="Top" Width="50" FontSize="20" FontFamily="Segoe UI Light" Style="{StaticResource ButtonStyle}"/>
    <Button Content="T" HorizontalAlignment="Left" Height="47" Margin="323,59,0,0" VerticalAlignment="Top" Width="50" FontSize="20" FontFamily="Segoe UI Light" Style="{StaticResource ButtonStyle}"/>
    <Button Content="R" HorizontalAlignment="Left" Height="47" Margin="268,59,0,0" VerticalAlignment="Top" Width="50" FontSize="20" FontFamily="Segoe UI Light" Style="{StaticResource ButtonStyle}"/>
    <Button Content="E" HorizontalAlignment="Left" Height="47" Margin="213,59,0,0" VerticalAlignment="Top" Width="50" FontSize="20" FontFamily="Segoe UI Light" Style="{StaticResource ButtonStyle}"/>
    <Button Content="W" HorizontalAlignment="Left" Height="47" Margin="158,59,0,0" VerticalAlignment="Top" Width="50" FontSize="20" FontFamily="Segoe UI Light" Style="{StaticResource ButtonStyle}"/>
</Grid>


text:
Q: Cold War SF about man and machine neural interface in aircraft It's an old work of Science Fiction (written during the Cold War).
The subject is men & machine interface.
The plot is as follows:

*

*An American pilot flies on a bombing mission to and over Russia.

*The aircraft and he are connected together by the neural networks and they are actually one!

*All kind of problems, thoughts and mishaps happen to them during this flight.

Question: What is the name of the book and/or the author?

A: This sounds like Firefox, a 1977 novel by Craig Thomas, made into a 1982 film starring Clint Eastwood.  It's about a plot to steal a Soviet fighter jet that has an experimental thought-controlled interface.
A key point in choosing the American pilot for the mission is that the interface requires the pilot to think in Russian.

A: A book with similar details is The Day of the Cheetah, a 1989 novel by Dale Brown.

His job at the secret base involves testing the highly advanced
  XF-34 Dreamstar, which is equipped with a thought-control interface.
James hijacks the fighter, causing Patrick McLanahan and the rest of
  the HAWC crew to try to recover or destroy the plane before it reaches
  the USSR.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I disable emacs dialogue 'File XXX is really big, really wants to open it?' how can I disable this dialogue 'File XXX is really big, really wants to open it?' whenever I open a big file?
Thank you.

A: Set the following in your .emacs file:
(setq large-file-warning-threshold nil)


text:
Q: How to get rect of a pygame Surface without transparent parts? I am implementing collision detection and want to check if a rectangular object is touching the player. My wall uses .set_colorkey(background) where background is the specified background colour. The problem is that when I get my wall's rectangle with .get_rect(), it gets the full image's size which includes the transparent parts instead of just the opaque parts.
I thought about making the wall image file smaller in size to remove the background but that would be inconvenient as I would need to do this for each partially transparent image I have. I also thought about using arrays to get the colour and checking if it matches the background colour and getting the rectangle's size from there but that would be slow and cumbersome.
for x, y in ((i, j) for i in land_x for j in land_y):
# land_x, land_y hold the tiles to be checked
    try:
        tx1, ty1, tx2, ty2 = \
             texture[land[y][x]].get_rect()
        # tx1, ty1 coordinates of top-left corner
        # tx2, ty2 width and height respectively
        if tx2 == 0 and ty2 == 0:
            continue    # skip to other objects
        tx1 = x*64 - tx2/2
        ty1 = y*64 - ty2/2
        px1, py1, px2, py2 = \
             PLAYER.get_rect()
        px1 = player_x - px2/2
        py1 = -player_y - py2/2
        if p.Rect(px1, py1, px2, py2).colliderect(
            p.Rect(tx1, ty1, tx2, ty2)
        ):
            player_x -= direction_x
            break    # go outside loop to start checking y
    except IndexError:    # incase player is outside map
        pass    # skip to other objects

The .get_rect() outputs a rectangle the size of the whole image whereas I want a rectangle that doesn't include the transparent parts.
Example:
texture is a 64x64 image with a 48x48 block in the centre.
The background colour is removed and a 48x48 solid coloured block is left (even though the image size is still 64x64).
Expected Output:
texture.get_rect() should output a rectangle of size 48x48.
Actual Output:
texture.get_rect() instead outputs a rectangle of size 64x64.
Any help on this would be appreciated :D

A: You are making this too hard.  You know the size of your objects. Add a smaller collision rect to each of your objects at creation time and use that for collision.  Or use a circle if that is better for the object.
tile.crect = Rect(whatever)

Or just multiply the existing rect dimensions by some scale factor for your collision rect. Don't do all of these calculations.  Store a Rect for each collideable object and have a rect for the player.
    tx1 = x*64 - tx2/2
    ty1 = y*64 - ty2/2
    px1, py1, px2, py2 = \
         PLAYER.get_rect()
    px1 = player_x - px2/2
    py1 = -player_y - py2/2

Then just test collision directly:
for t in tiles:
    if player.rect.colliderect( t.rect ):

If the player is a sprite its rect moves around. Look at the example code in the doc.
https://www.pygame.org/docs/ref/sprite.html

A: If you want to ignore the transparent pixels in your collision detection, you're talking about pixel-perfect collision.
To do this in pygame, pygame offers the Mask class. You usually create your masks with pygame.mask.from_surface and use it together with pygame.sprite.spritecollide and pygame.sprite.collide_mask.
Maybe think about using pygame's Sprite class to make use of all the features it offers.
Even if you don't want to use pygame's build-in collision detection, you can take a look at the source to see how it works.


text: Q: Single post shows post three times Not sure exactly what happened, but my site shows the single post content multiple times. Example. Reinstalling the theme didn't help. Also, it's not happening with any other theme, only with the current one. No plugins are active. Not sure what could be the problem.


text:
Q: Grails 3.* - Creating custom property file and read the data I am  using Grails 3.1, trying to create a custom property file and read the data present in that file.
File myapp.properties is located in the config directory and contains data such as
name = "abc"

I want to read the data in my controller.
Any suggestions is appreciated

A: Easiest way is probably with Spring Boot's @ConfigurationProperties.
Put your myapp.properties in src/main/resources then create a configuration class:
@ConfigurationProperties(locations=['classpath:myapp.properties'])
class MyConfiguration {
   String name
}

Add it as a Spring bean in grails-app/resources.groovy
myConfiguration(MyConfiguration)

Auto wire it into a controller or service:
@Autowired
MyConfiguration myConfiguration

def foo() {
   render myConfiguration.name
}


text:
Q: Postgresql: "error syntax error at end of input" I'm trying to connect to PostgreSQL database and get an error saying pq: syntax error at end of input
package utils

// DBConnect connection to PG database
func DBConnect() *sql.DB {
    // env := LoadEnvVariables()

    connStr := "postgres://user:password@127.0.0.1/lybl?sslmode=disable"
    fmt.Println(connStr)

    db, err := sql.Open("postgres", connStr)
    if err != nil {
        log.Fatal(err)
        return nil
    }

    return db
}

Don't know what I'm missing here


text:
Q: How does the Free monad and Reactive Extensions correlate? I come from a C# background, where LINQ evolved into Rx.NET, but always had some interest in FP. After some introduction to monads and some side-projects in F#, I was ready to try and step to the next level.
Now, after several talks on the free monad from people from Scala, and multiple writeups in Haskell, or F#, I have found grammars with interpreters on for comprehension to be quite similar to IObservable chains.
In FRP you compose an operation definition from smaller domain specific chunks including side-effects and failures that stay inside the chain, and model your application as a set of operations and side effects. In free monad, if I understood correctly, you do the same by making your operations as functors, and lifting them using coyoneda.
What would be the differences between both that tilt the needle towards any of the approaches? What is the fundamental difference when defining your service or program?

A: Monads
A monad consists of

*

*An endofunctor.  In our software engineering world, we can say this corresponds to a datatype with a single, unrestricted type parameter.  In C#, this would be something of the form:
class M<T> { ... }

*Two operations defined over that datatype:

*

*return / pure takes a "pure" value (i.e., a T value) and "wraps" it into the monad (i.e., it produces an M<T> value).  Since return is a reserved keyword in C#, I'll use pure to refer to this operation from now on.  In C#, pure would be a method with a signature like:
M<T> pure(T v);

*bind / flatmap takes a monadic value (M<A>) and a function f.  f takes a pure value and returns a monadic value (M<B>).  From these, bind produces a new monadic value (M<B>).  bind has the following C# signature:
M<B> bind(M<A> mv, Func<A, M<B>> f);

Also, to be a monad, pure and bind are required to obey the three monad laws.
Now, one way to model monads in C# would be to construct an interface:
interface Monad<M> {
  M<T> pure(T v);
  M<B> bind(M<A> mv, Func<A, M<B>> f);
}

(Note:  In order to keep things brief and expressive, I'll be taking some liberties with the code throughout this answer.)
Now we can implement monads for concrete datagypes by implementing concrete implementations of Monad<M>.  For instance, we might implement the following monad for IEnumerable:
class IEnumerableM implements Monad<IEnumerable> {
  IEnumerable<T> pure(T v) {
    return (new List<T>(){v}).AsReadOnly();
  }

  IEnumerable<B> bind(IEnumerable<A> mv, Func<A, IEnumerable<B>> f) {
    ;; equivalent to mv.SelectMany(f)
    return (from a in mv
            from b in f(a)
            select b);
  }
}

(I'm purposefully using the LINQ syntax to call out the relationship between LINQ syntax and monads.  But note we could replace the LINQ query with a call to SelectMany.)
Now, can we define a monad for IObservable?  It would seem so:
class IObservableM implements Monad<IObservable> {
  IObservable<T> pure(T v){
    Observable.Return(v);
  }

  IObservable<B> bind(IObservable<A> mv, Func<A, IObservable<B>> f){
    mv.SelectMany(f);
  }
}

To be sure we have a monad, we need to prove the monad laws.  This can be non-trivial (and I'm not familiar enough with Rx.NET to know whether they can even be proved from the specification alone), but it's a promising start.  To facilitate the remainder of this discussion, let's just assume the monad laws hold in this case.
Free Monads
There is no singular "free monad".  Rather, free monads are a class of monads that are constructed from functors.  That is, given a functor F, we can automatically derive a monad for F (i.e., the free monad of F).
Functors
Like monads, functors can be defined by the following three items:

*

*A datatype, parameterized over a single, unrestricted type variable.

*Two operations:

*

*pure wraps a pure value into the functor.  This is analogous to pure for a monad.  In fact, for functors that are also a monads, the two should be identical.

*fmap maps values in the input to new values in the output via a given function.  It's signature is:
F<B> fmap(Func<A, B> f, F<A> fv)

Like monads, functors are required to obey the functor laws.
Similar to monads, we can model functors via the following interface:
interface Functor<F> {
  F<T> pure(T v);
  F<B> fmap(Func<A, B> f, F<A> fv);
}

Now, since monads are a sub-class of functors, we could also refactor Monad a bit:
interface Monad<M> extends Functor<M> {
  M<T> join(M<M<T>> mmv) {
    Func<T, T> identity = (x => x);
    return mmv.bind(x => x); // identity function
  }

  M<B> bind(M<A> mv, Func<A, M<B>> f) {
    join(fmap(f, mv));
  }
}

Here I've added an additional method, join, and provided default implementations of both join and bind.  Note, however, that these are circular definitions.  So you'd have to override at least one or the other.  Also, note that pure is now inherited from Functor.
IObservable and Free Monads
Now, since we have defined a monad for IObservable and since monads are a sub-class of functors, it follows that we must be able to define a functor instance for IObservable.  Here's one definition:
class IObservableF implements Functor<IObservable> {
  IObservable<T> pure(T v) {
    return Observable.Return(v);
  }

  IObservable<B> fmap(Func<A, B> f, IObservable<A> fv){
    return fv.Select(f);
  }
}

Now that we have a functor defined for IObservable, we can construct a free monad from that functor.  And that is precisely how IObservable relates to free monads — namely, that we can construct a free monad from IObservable.


text:
Q: Generating temporary URI for object using BlobStore I am trying to implement a generation of a temporary GET URIs for objects stored in the OpenStack Swift container using jClouds BlobStore features.
However I am getting these errors:
java.lang.IllegalStateException: Suppliers.memoizeWithExpiration(get().getTemporaryUrlKey() using {annotationParser={caller=SwiftApi.accountApiInRegion[RegionOne]}}, 60000000000, NANOS) returned a null temporaryUrlKey!
    at com.google.common.base.Preconditions.checkState(Preconditions.java:177)
    at org.jclouds.openstack.swift.v1.TemporaryUrlSigner.hmacSHA1(TemporaryUrlSigner.java:63)
    at org.jclouds.openstack.swift.v1.TemporaryUrlSigner.sign(TemporaryUrlSigner.java:57)
    at org.jclouds.openstack.swift.v1.blobstore.RegionScopedTemporaryUrlBlobSigner.sign(RegionScopedTemporaryUrlBlobSigner.java:100)
    at org.jclouds.openstack.swift.v1.blobstore.RegionScopedTemporaryUrlBlobSigner.signGetBlob(RegionScopedTemporaryUrlBlobSigner.java:73)

Here comes a code sample:
public class BlobStoreObjectSignerService implements ObjectSignerService {

    @Autowired
    private BlobRequestSigner blobRequestSigner;

    @Value("${blobStore.private.container}")
    String privateContainerName;

    /**
    * Generates signed request With GET Method to access allocated object.
    *
    * @param objectName         name of the stored file
    * @param principalName      name of the principal (user) which is putted the file
    * @param temporary          defines if file should be available for a limited time
    * @param timeToLive         time in seconds file will be available for fetching
    */
    public HttpRequest generateGetRequestForObject( String objectName,
                                                    String principalName,
                                                    boolean temporary,
                                                    long timeToLive ) {
        if (temporary) {
            return this.generateTemporaryGetRequestForObject(objectName,  principalName, timeToLive);
        } else {
            return this.generatePermanentGetRequestForObject(objectName,  principalName);
        }
    }

    public HttpRequest generatePermanentGetRequestForObject( String objectName,
                                                             String principalName ) {
        return this.generatePermanentGetRequestForObject( privateContainerName,
                                                          String.format( "/%s/%s", principalName, objectName ) );
    }

    public HttpRequest generateTemporaryGetRequestForObject( String objectName,
                                                             String principalName,
                                                             long timeToLive ) {
        return this.generateTemporaryGetRequestForObject( privateContainerName,
                                                          String.format( "/%s/%s", principalName, objectName ),
                                                          timeToLive );
    }

    public HttpRequest generatePermanentGetRequestForObject(String containerName, String objectName) {
        return this.blobRequestSigner.signGetBlob(containerName, objectName);
    }

    public HttpRequest generateTemporaryGetRequestForObject(String containerName, String objectName, long timeToLive) {
        return this.blobRequestSigner.signGetBlob(containerName, objectName, timeToLive);
    }

}

As for public containers i can still get object links by fetching header/metadata, and it is kind of sideway, but i am still in need of signed URIs to publish objects stored in private containers.
Putting files into container using BlobStore is working just fine. All pushed are normally dislayed by OpenStack Dashboard.
I am using Java 7 and DevStack configurated for Swift only in dev environment.
jClouds version is 1.7.2.

A: Based on the exception, it looks like you don't have a temporary URL Key set on the Account. You can update the key to a new value via the AccountApi like this:
SwiftApi swiftApi = ContextBuilder.newBuilder(PROVIDER)
           .credentials("{username}", "{apiKey}")
           .buildApi(SwiftApi.class);

// Access the accountApi
AccountApi accountApi = swiftApi.getAccountApiForRegion("{regionId");
accountApi.updateTemporaryUrlKey("{newKey}");

// Access the key
String tempUrlKey;
if (accountApi.getTemporaryUrlKey().isPresent()) {
   tempUrlKey = accountApi.get().getTemporaryUrlKey().get();
}

Hope that helps!


text:
Q: CSS speed optimisation - Why multiple files are better then only one? Less HTTP request the better it's, right ?
Regarding to Google best practice explanation, less unused css rules is also better.

*

*The browser's CSS engine has to evaluate every rule contained in the file to see if the rule applies to the current page.

*Even if a stylesheet is in an external file that is cached, rendering is blocked until the browser loads the stylesheet from disk.

In your opinion what's giving better performance :

*

*One css file per page.

*One general css that will be cached (even if there will be +70% unused css / but avoiding any other http requests).

Google speed best-practice

A: One of the important sentence to note from the Google best practice document is "Often, many web sites reuse the same external CSS file for all of their pages, even if many of the rules defined in it don't apply to the current page".
This needs to be taken into account as if the css file has additional code that is never going to be used if user does not visit the page for which this redundant code applies then we are certainly wasting the bandwidth which may not be a proper trade off for an additional HTTP request.
This leads to additional time to load the file plus the time wasted in evaluation of that redundant code.
Certainly using multiple files for just a single page (like different header/footer css files) would be a bad practice.
And as you know that there is not a perfect solution for any problem. You have to choose the best thing that suits your need.
So, I would say the decision to use multiple files or a single file is solely based on the overall structure of website and other trade offs.

A: Loading CSS is usually extremely quick. CSS blocking is something you will probably never catch. Whereas JavaScript could do so that you are visually aware that it's being downloaded. (white spaces while rendering the page).
In reality one CSS is good enough, because of a single HTTP request.
Optimization should go towards JavaScript, because this is where you can see the page slowing down. We are talking about a second-two of a difference or less here.
Here is a site where you can enter URL and it will check load times. In the graph below you can compare CSS load times.


text:
Q: Is there any regular expression for finding and extract the string from a text I have a List of paths stored in a text file. I am trying to extract the full path from this text using a regular expression.
The text file data
/IVTP/DB_db/0171-0_7-296&519_510&586-501&586_296&585_305&519_510&520-0_9_25_31_33_33_32-205-35.jpg
/IVTP/DB_db/0069-0_2-450&447_581&491-579&491_450&490_452&447_581&448-0_0_9_29_17_24_30-209-15.jpg
/IVTP/DB_base/0395-4_7-175&502_475&612-456&612_175&590_194&502_475&524-10_0_9_14_26_27_27-206-22.jpg
/IVTP/DB_base/0234-7_21-271&499_461&602-461&602_291&580_271&499_441&521-0_0_1_32_31_31_18-215-37.jpg
/IVTP/DB_cc/0291-0_7-271&483_527&578-517&574_271&578_281&487_527&483-0_0_20_29_33_26_18-212-93.jpg
/IVTP/DB_cc/0325-1_6-227&475_507&572-499&565_227&572_235&482_507&475-0_0_23_28_33_25_33-212-30.jpg

I read the file as Text
imgs_abs_path = [line.strip() for line in open('/home/img_data.txt', 'r') if line.strip() != '']
#converting the list to string
imgs_paths_to_str = ",".join(str(x) for x in imgs_data_abs_path)
# lis the images from the dataset
imgs_data = [f for f in os.listdir('.') if f.endswith('.jpg')]

My problem
After reading each image, I want to check if the name exists in the text file using a regular expression. If it does, then I want to extract the absolute path from the text file.

I used this regular expression but it always return empty
"(/IVTP/*"+img+")"

My code
new_list = []
for img in imgs_data:
   if search(img, imgs_paths_to_str):
       regex = "(/IVTP/*"+img+")"
       new_list.append(re.findall(regex, imgs_paths_to_str))

print(print(new_list))
[]

A: I suggest adding the paths from the text file into imgs_paths_to_str list, not a string, and then just check agains the files found in the current directory, and only keep those that start with your required prefix and end with the file name found in the directory:
imgs_paths_to_str = []

with open('/home/img_data.txt', 'r') as f:
    for line in f:
        line = line.strip()
        if line:
            imgs_paths_to_str.append(line)

imgs_data = [f for f in os.listdir('.') if f.endswith('.jpg')]

new_list = []
for img in imgs_data:
    for ipts in imgs_paths_to_str:
        if ipts.startswith('/IVTP/') and ipts.endswith(img):
            print(ipts) # new_list.append(ipts)

See the Python demo.


text:
Q: frcursive package scaling I recently found this package frcursive which I think gives beautiful caligraphic letters.
The only problem is when I try to use it, the capital calligraphic letters are too big compared to normal capital letters ! Can anyone help me scaling them down, leaving the lowercase letter untouched ?
Here is a MWE
\documentclass[12pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{frcursive}
\begin{document}
\cursive{A}A
\end{document}

Thanks for the help
T.D

A: You can load the fonts at a suitable scale (2/3 seems good).
\documentclass[12pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}

\DeclareFontFamily{T1}{frc}{}
\DeclareFontShape{T1}{frc}{m}{n}{%
  <-8>   s*[0.6667] frcr6
  <8-14> s*[0.6667] frcr10
  <14->  s*[0.6667] frcr14
}{}
\DeclareFontShape{T1}{frc}{m}{sl}{%
  <-8>   s*[0.6667] frcsl6
  <8-14> s*[0.6667] frcsl10
  <14->  s*[0.6667] frcsl14
}{}
\DeclareFontShape{T1}{frc}{m}{it}{<-> ssub*frc/m/sl}{}
\DeclareFontShape{T1}{frc}{bx}{n}{%
  <-8>   s*[0.6667] frcbx6
  <8-14> s*[0.6667] frcbx10
  <14->  s*[0.6667] frcbx14
}{}
\DeclareFontShape{T1}{frc}{bx}{sl}{%
  <-8>   s*[0.6667] frcbxsl6
  <8-14> s*[0.6667] frcbxsl10
  <14->  s*[0.6667] frcbxsl14
}{}
\DeclareFontShape{T1}{frc}{bx}{it}{<-> ssub*frc/bx/sl}{}

\DeclareRobustCommand{\cursive}{\fontfamily{frc}\selectfont}
\DeclareTextFontCommand{\textcursive}{\cursive}

\begin{document}

\textcursive{ABCD}A

\textit{\textcursive{ABCD}A}

\textbf{\textcursive{ABCD}A}

\end{document}

About scaling only the uppercase letters, I don't think that it can give a nice result: it's pretty ugly, to be honest:

A: \documentclass[12pt, a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage{frcursive}
\makeatletter
\renewenvironment{cursive}{%
  \fontencoding{\frcursive@enc}%
  \fontfamily{frc}%
  \fontsize{9pt}{10pt}%
  \linespread{1.5}%
  \selectfont}{\par}
 \makeatother
\begin{document}
A \begin{cursive} A \end{cursive}
\end{document}


text:
Q: Cannot add values to Redis cluster - The cluster is down I have 4 nodes, 3 are master and 1 of them is a slave. I am trying to add a simple string by set foo bar, but whenever i do it, i get this error:
(error) CLUSTERDOWN The cluster is down

Below is my cluster info
127.0.0.1:7000cluster info

cluster_state:fail

cluster_slots_assigned:11

cluster_slots_ok:11

cluster_slots_pfail:0

cluster_slots_fail:0

cluster_known_nodes:4

cluster_size:3

cluster_current_epoch:3

cluster_my_epoch:3

cluster_stats_messages_sent:9262

cluster_stats_messages_received:9160

I am using Redis-x64-3.0.503. please let me know how to solve this
Cluster Nodes:
87982f22cf8fb12c1247a74a2c26cdd1b84a3b88 192.168.2.32:7000 slave bc1c56ef4598fb4ef9d26c804c5fabd462415f71 1492000375488 1492000374508 3 connected

9527ba919a8dcfaeb33d25ef805e0f679276dc8d 192.168.2.35:7000 master - 1492000375488 1492000374508 2 connected 16380

ff999fd6cbe0e843d1a49f7bbac1cb759c3a2d47 192.168.2.33:7000 master - 1492000375488 1492000374508 0 connected 16381

bc1c56ef4598fb4ef9d26c804c5fabd462415f71 127.0.0.1:7000 myself,master - 0 0 3 connected 1-8 16383

A: Just to add up and simplify what @neuront said.
Redis stores data in hash slots. For this to understand you need to know how Hasmaps or Hashtables work. For our reference here redis has a constant of 16384 slots to assign and distribute to all the masters servers.
Now if we look at the node configuration you posted and refer it with redis documentation, you'll see the end numbers mean the slots assigned to the masters.
In your case this is what it looks like
... slave  ... connected
... master ... connected 16380
... master ... connected 16381
... master ... connected 1-8 16380

So all the machines are connected to form up the cluster but not all the hash slots are assigned to store the information. It should've been something like this
... slave  ... connected
... master ... connected 1-5461
... master ... connected 5462-10922
... master ... connected 10923-16384

You see, now we are assigning the range of all the hash slots like the documentation says

slot: A hash slot number or range. Starting from argument number 9, but there may be up to 16384 entries in total (limit never reached). This is the list of hash slots served by this node. If the entry is just a number, is parsed as such. If it is a range, it is in the form start-end, and means that the node is responsible for all the hash slots from start to end including the start and end values.

For specifically in your case, when you store some data with a key foo, it must've been assigned to some other slot not registered in the cluster.
Since you're in Windows, you'll have to manually setup the distribution. For that you'll have to do something like this (this is in Linux, translate to windows command)
for slot in {0..5400}; do redis-cli -h master1 -p 6379 CLUSTER ADDSLOTS $slot; done;

taken from this article
Hope it helped.

A: Only 11 slots were assigned so your cluster is down, just like the message tells you. The slots are 16380 at 192.168.2.35:7000, 16381 at 192.168.2.33:7000 and 1-8 16383 at 127.0.0.1:7000.
Of couse the direct reason is that you need to assign all 16384 slots (0-16383) to the cluster, but I think it was caused by a configuration mistake.
You have a node with a localhost address 127.0.0.1:7000. However, 192.168.2.33:7000 is also a 127.0.0.1:7000, while 192.168.2.35:7000 is also a 127.0.0.1:7000. This localhost address problem makes a node cannot tell itself from another node, and I think this causes the chaos.
I suggest you reset all the nodes by cluster reset commands and re-create the cluster again, and make sure you are using their 192.168.*.* address this time.

A: @user1829319 Here goes the windows equivalents for add slots:
for /l %s in (0, 1, 8191) do redis-cli -h 127.0.0.1 -p 6379 CLUSTER ADDSLOTS %s
for /l %s in (8192, 1, 16383) do redis-cli -h 127.0.0.1 -p 6380 CLUSTER ADDSLOTS %s

A: you should recreate your cluster by doing flush all and cluster reset and in next cluster setup make sure you verify all slots has been assigned to masters or not using > cluster slots


text:
Q: Isomorphism between $\operatorname{End}(F\otimes F)$ and $\operatorname{End}(F)\otimes \operatorname{End}(F)$, where F is an exact faithful functor. Let $\mathcal{C}$ be a finite $k$-linear abelian category, and $\operatorname{Vec}$ be the category of finite dimensional vector spaces over $k$. Let $F_1,\ F_2:\ \mathcal{C}\rightarrow \operatorname{Vec}$ be two $k$-linear exact faithful functors. Then $F_1\otimes F_2$: $\mathcal{C}\times\mathcal{C}\rightarrow\operatorname{Vec}$ is a functor, sending $(X,Y)$ to $F(X)\otimes_kF(Y)$ and $(f,g)$ to $f\otimes g$.
We denote $\operatorname{End}(F)$ as the algebra of natural transformations from $F$ to $F$. To understand the coalgebra structure of $\operatorname{End}(F)$ (when $\mathcal{C}$ is tensor catgeory), an important step is understanding the follow isomorphism:
\begin{align}
\Phi:\operatorname{End}(F_1)\otimes\operatorname{End}(F_2)&\longrightarrow\operatorname{End}(F_1\otimes F_2)\\
\alpha\otimes\beta&\longmapsto \Phi(\alpha\otimes\beta)_{(X,Y)}\!=\!\alpha_X\otimes\beta_Y\!\!: F_1(X)\otimes F_2(Y)\rightarrow F_1(X)\otimes F_2(Y)
\end{align}
It is easy to show that $\Phi$ is a well-defined linear map.(and an algebra map when $F_1=F_2$)
My question is: how to prove that $\Phi$ is isomorphic? I cannot do both injectivity and surjectivity.

A: Do you find a flaw in this argument?
Fact 0. $\hom(V,W)\cong V^\lor\otimes W$ ($V^\lor$=the dual of $V$).
Fact 1. $A \otimes-$ (tensoring with $A$) is a continuous functor, because it has $A^\lor\otimes-$ (tensoring with the dual of $A$) as left adjoint:
$$ \hom(X,A\otimes Y)\cong X^\lor\otimes A^{\lor\lor}\otimes Y\cong \hom(A^\lor \otimes X,Y)$$
Fact 2. For functors $H,K : {\cal C}\to Vect$,
$$ Nat(H,K) \cong \int_X Vect(HX,KX)$$
so in particular $End(F)\cong \int_XVect(FX,FX)$.

But now:
$$\begin{align*}
End(F)\otimes End(G) &\cong \int_X Vect(FX,FX)\otimes \int_YVect(GY,GY) \tag{fact2}\\
&\cong\int_X\int_Y\Big(Vect(FX,FX)\otimes Vect(GY,GY)\Big)\tag{fact1}\\
&\cong\int_X\int_Y(FX)^\lor\otimes FX\otimes (GY)^\lor \otimes GY\tag{fact0}\\
&\cong\int_X\int_Y(FX)^\lor\otimes (GY)^\lor\otimes FX \otimes GY\tag{sym-$\otimes$}\\
&\cong\int_X\int_Y(FX \otimes GY)^\lor\otimes FX \otimes GY\tag{$\lor$-$\otimes$}\\
&\cong\int_{XY}(FX \otimes GY)^\lor\otimes FX \otimes GY\tag{Fubini}\\
&\cong\int_{XY}Vect(FX \otimes GY, FX \otimes GY)\tag{fact0}\\
&\cong End(F\otimes G)\tag{fact2}\\
\end{align*}$$


text:
Q: Terminal does not appear and package management is broken after I removed python3.5 and installed python3.6 Recently I removed python3.5 and installed python3.6 using conda. Now terminal doesn't start and I can see a red error button at top right corner that says

A Problem occurred when checking for the updates

How can I fix it?


text:
Q: how to get data with relation in Laravel trying to get Bill Products to view I have 3 models connected together Vendors has many Bills and bills has many bill_products
what do I need is to display the data with this relation in the index view here is my controller index function
    public function index()
    {
        $vendor = $this->vendor();
        $data['vendor_id'] = $vendor->id;
        $data['bills'] = $vendor->bills()->get();
        return view('vendors.bills.index', $data);
    }

this bills relation in vendor model
   public function bills()
    {
        return $this->hasMany(VendorBill::class);
    }

Vendor bills model where I put my relation to bill products
class VendorBill extends Model
{
    const FILLABLE = [
        'making_cost',
        'gram_price',
        'customer_name',
        'customer_id',
        'vendor_id',
        'id_no',
        'phone',
        'bill_no',
        'total',
    ];
    protected $fillable = self::FILLABLE;

    public function vendor()
    {
        return $this->belongsTo(Vendor::class);
    }
    public function billProducts()
    {
        return $this->hasMany(VendorBillProduct::class);
    }
}

and this is the last Model that belongs to Vendor Bills where i need to get data from
class VendorBillProduct extends Model
{
    use SoftDeletes;

    protected $table = "bill_products";

    const FILLABLE = [
        'vendor_bill_id',
        'cate_code',
        'product_description',
        'metal_weight',
        'total_metal_weight',
        'caliber',
        'gem_stone_weight',
        'diamond_weight',
        'purity',
        'color',
        'dimond',
    ];
    protected $fillable = self::FILLABLE;

    public function vendorBill()
    {
        return $this->belongsTo(VendorBill::class);
    }
}

this is the index blade view where I want to get data stored in BillProducts the belongs to the VendorBill

                @lang('vendors.bill_no')
                @lang('vendors.customer')
                @lang('vendors.phone')
                @lang('vendors.cate_code')
                @lang('vendors.action')

            @if($bills->count())
                @foreach(@$bills as $bill)

                        {{@$bill->bill_no}}
                        {{@$bill->customer_name}}
                        {{@$bill->phone}}
                        {{@$bill->cate_code}}

                                    id)}}" class="dropdown-item" type="button">
                                        @lang('vendors.edit')

                                    id)}}">@lang('vendors.details')
                                    {{--<button class="dropdown-item" type="button">
                                        @lang('vendors.delete')
                                    </button>--}}

                @endforeach
            @endif

enter image description here
in this image, I highlighted the column that I need to get in relation

A: I think there is a clever solution within your problem. Create a method on your VendorBill.php model, that concats the codes.
class VendorBill
{
    function concatCodes(): string
    {
        return $this->billProducts->pluck('cate_code')->implode(', ');
    }
}

Now in the context of a bill, you can convert all its vendor bills into that string and then implode that.
$bill->map->concatCodes()->implode(', ');

This will then concat the codes into the a string similar to this
code1, code2, code3


text:
Q: How to store token in react I saved token in localStorage:
localStorage.setItem('token', response.data.token)

and i want send token in every request, i added this to index.js
const token = localStorage.getItem('token');
if (token) {
    axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;
}

when start project, if token existed, axios send token in every request, but when i add token after start project, axiost don't send token, can i refresh default config after started project?

A: this is my abstraction of Axios request, this allow auth token to be added or changed any time:
import axios from 'axios';
import { API } from '../../constants';
import { store } from '../../../configureStore';

import { revokeAuthAction } from '../../../containers/Auth/actions';

export const getAuth = () => {
  const sessionString = localStorage.getItem('session');
  let auth;
  if (sessionString) {
    const session = JSON.parse(sessionString);
    auth = `${session.nation}|${session.user}|${session.token}`;
  }
  return auth;
};

/**
 * Create an Axios Client with defaults
 */
const client = axios.create({
  baseURL: API.BASEURL,
  headers: {
    Authorization: getAuth(),
    'Access-Control-Max-Age': 1728000,
  },
});

/**
 * Request Wrapper with default success/error actions
 */
const request = (options) => {
  const onSuccess = (response) => options.raw ? response : response.data;
    // console.debug('Request Successful!', response);
    // If options.raw is true, return all response

  const onError = (error) => {
    // console.error('Request Failed:', error.config);

    if (error.response) {
      if (error.response.status === 401) {
        // console.error('Unauthorized');
        store.dispatch(revokeAuthAction());
      } else {
        // Request was made but server responded with something
        // other than 2xx
        // console.error('Status:', error.response.status);
        // console.error('Data:', error.response.data);
        // console.error('Headers:', error.response.headers);
      }
    } else {
      // Something else happened while setting up the request
      // triggered the error
      // console.error('Error Message:', error.message);
    }

    return Promise.reject(error.response || error.message);
  };

  return client(options)
    .then(onSuccess)
    .catch(onError);
};

export default request;

Usage:
import request from '../../../../shared/lib/request';

[...]

const create = (content) => request(
  {
    url: API.MY_ENDPOINT,
    method: 'POST',
    data: content,
  });


text:
Q: Angular 2 model into a function I pull data from my firebase database.
This is my service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import {Http, Response, RequestOptions} from '@angular/http';
import { RealEstatePhotography } from './real-estate-photography';
import {AngularFire, FirebaseListObservable} from 'angularfire2';
import 'rxjs/add/operator/map';

@Injectable()
export class RealEstatePhotographyService {

  constructor(private af: AngularFire, private http: Http) { }

private realEstate =  this.af.database.list('realestate');

  getItems(){
    return (this.realEstate);
  }

  getItem(title: RealEstatePhotography) : Observable<any>{
    return this.realEstate
    .map((list: Array<any>) => {
      let result: RealEstatePhotography = new RealEstatePhotography();
      if (list){
        list.forEach(element => {
          if (element.title === title){
            result = element
          }
        });
        return result;
      }
    });
  }
}

this is my detail component:

import { Component,  OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl, SafeUrl, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { RealEstatePhotography } from '../real-estate-photography';
import { RealEstatePhotographyService } from '../real-estate-photography.service';

@Component({
  selector: 'app-real-estate-photography-detail',
  templateUrl: './real-estate-photography-detail.component.html',
  styleUrls: ['./real-estate-photography-detail.component.css'],
  providers: [RealEstatePhotographyService],
})
export class RealEstatePhotographyDetailComponent implements OnInit {

photos = this.photo();
realEstate;

  constructor(private route: ActivatedRoute, private _realEstatePhotographyService: RealEstatePhotographyService, private sanitizer: DomSanitizer) { }

  photo(){
    var location = ""
    for (var i = 0; i < location.length; i++){
      Array(i);
    }
    return console.log(Array(i));

  }

  ngOnInit(){
    this.route.params.subscribe(params => {
      let title = params['title'];
      let realEstate = this._realEstatePhotographyService.getItem(title).subscribe(realEstate => {
        this.realEstate = realEstate

      });
    });
  }
}

this is my html from that component.

<p>{{realEstate.folder}}</p>

This is the data I get:

Now, my question is. I need to put that result into the "location" variable i have in the photo() function.
something like var location = this.realEstate.folder or {{realEstate.folder}}
I can't figure out how to do it.
Thank you
here is a plunk but, of course, does not return into anything because i am not connected to firebase
https://plnkr.co/edit/a0WKevpXpwvY8x7NG1cb?p=preview

A: I'm not completely clear on what you are trying to do, but perhaps this might get you closer?
Note that this.location will be 'undefined' until your observable returns data. If you are using this in the template you can use *ngIf="location" on the tag.
    export class RealEstatePhotographyDetailComponent implements OnInit {

    photos = this.photo();
    realEstate;
    private location: any;

      constructor(private route: ActivatedRoute, private _realEstatePhotographyService: RealEstatePhotographyService, private sanitizer: DomSanitizer) { }

      photo(){

if(this.location) {

        for (var i = 0; i < this.location.length; i++){
          Array(i);
        }
        return console.log(Array(i));
    }
      }

      ngOnInit(){
        this.route.params.subscribe(params => {
          let title = params['title'];
          let realEstate = this._realEstatePhotographyService.getItem(title).subscribe(realEstate => {
            this.realEstate = realEstate
    this.location=realEstate.folder;
          });
        });
      }
    }


text:
Q: How to start with a blank main window? I want to write some VBA script so that when I start my access application the main window is blank. This is the list of things I need to be removed or hidden:

*

*The entire ribbon

*The status bar

*The navigation pane

*The window tabs

In addition, I want to disable the popup menu when right clicking.
I also want to disable SHIFT bypass key startup.
I basically want it to look like an application created with VB or C#.
Only if I login as admin will the disabled options be bypassed.

A: Does it need to be VBA? Why not using the normal Access Application Options?
In Access 2010 you can find them via File > Options > Current Database. Almost all the things you want can just be unchecked - see the following screenshot. The options you select there are saved with your database.
You can start the database while holding SHIFT which will override these start up options and show you your "normal" ribbon, status bar, navigation bar, ...

A: Try the following in startup function
This should do what you want
DoCmd.ShowToolbar "Ribbon", acToolbarNo
DoCmd.ShowToolbar "Status Bar", acToolbarNo

Might work with other MS Access windows elements, I just wanted to not display the parts above.

A: Old thread but still useful information. Here's what I do:
DoCmd.ShowToolbar "Ribbon", acToolbarNo
DoCmd.ShowToolbar "Status Bar", acToolbarNo
DoCmd.NavigateTo "acNavigationCategoryObjectType"
DoCmd.RunCommand acCmdWindowHide

Put that code in a Public Sub called from a macro called AutoExec.
Disabling Window Tabs and the Shift Bypass are trickier because these need to be done by setting the database property, either through the database Properties or by appending a property with CreateProperty. Also, you need to exit and reopen the database for these changes to take effect.
I found instructions over on techrepublic and Allen Browne has more complete instructions on his website.

A: Actually, as noted, you can use the startup options to remove most all of the questions you have in terms of popups, the tabs etc.
To hide ribbon, qat, just use:
DoCmd.ShowToolbar "Ribbon", acToolbarNo
So, with the options setup  correct and ONE line of code, you only see your form.
Here is an resulting screen shot of using the above one line of code and options to turn off tabs (you want tabbed windows, but tabs turned off). Note how you see the windows desktop. this was all done with one line of code as per above:


text:
Q: Back button Launches Splash Screen I am developing Phonegap 2.7.0 + Android Application.
Problem is when I am on index.html page of my application and I press back button of device  it Launches Splash Screen and ReInitiate Application.

A: From the Phonegap side, you could attach a handler function to the backbutton, something like this:
function exitApp() {
    console.log("Exiting app");
    navigator.app.exitApp();
}

function onPressBack(e) {
    e.preventDefault();
    navigator.notification.confirm("Are you sure you want to quit?", function(result){
        if(result == 2){
            exitApp();
        }
    }, 'Quit My App', 'Cancel,Ok');
}

function deviceready() {
    $(document).bind('backbutton', onPressBack);
}
$(document).bind('deviceready', deviceready);

If you're using jQuery Mobile for paging, you can keep track of whether it's the first page being shown and therefore whether to show the exit dialog - see my answer to this question

A: You should call finish() or this.finish() after calling the startActivity(intent) method.
Something like this:
Intent intent = new Intent(currentActivity.this, activityToBeCalled.class) ;
startActivity(intent) ;
finish() ;

A: Use finish() in splash screen activity

A:   @Override
  protected void onPause()
  {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
  }

add this event to your splash activity class.
Edit: you can add activity events by right clicking and following "Source->Overwrite/Implements Methods...".
http://developer.android.com/images/activity_lifecycle.png
and then you should add this event to your webview activty
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    return super.onKeyDown(keyCode, event);

    // do not finish app use webview controls to go preview webpage.
}


text:
Q: How does file creation work in Java I am trying to create a file using

File newFile = new File("myFile");

However no file called "myFile" is created. This is within a Web application Project i.e. proper form to be pakaged as a WAR but I am calling it as part of a main method (just to see how this works).
How can I make it so that a new file is created at a location relative to the current one i.e not have to put in an absolute path.
EDIT:

newFile.createFile();

Doesn't seem to work:
Here is the entire code:
import java.io.File;
import java.io.IOException;

public class Tester {

public static void main(String[] args) throws IOException{
    Tester test = new Tester();
    test.makeFile();
}

public void makeFile() throws IOException{
    File newFile = new File("myFile");
    newFile.createNewFile();
    }
}

A: In answer to your comment. The file will be created in the current directory of the process, unless you specifiy otherwise.
// new file in current directory
File f = new File("yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());

To create it in a directory of your choosing:
File f = new File("c:\\yourDirectory","yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());

A: you could use newFile.createNewFile();

A: newFile.createNewFile();


text:
Q: How to identify the values of a resistor with printed markings? I'm trying to fix my Silverstone SST-ST60F-P 600w power supply which has a burnt resistor. It just so happens I have another psu of the same model so I opened it up to look for the value of the burnt resistor since I can't read the values anymore. The problem is it's not like the usual resistor which is color coded. It has numbers printed on it.

The values listed on the resistor are R207 337Y. It does have a silver band which should mean it's tolerance is 10% but I'm not sure.

A: That's a diode. R207 is the part number. The band marks the cathode.


text:
Q: Reducibility of a variety Suppose $X$ is a variety defined in $\mathbb P^n\times\mathbb P^n$ by a divisor.  It projects down to first $\mathbb P^n$ almost every fiber is not $\mathbb P^n$ and assume every fiber is reducible.  Is $X$ is reducible?

A: As Vesselin Dimitrov remarked, this fails for $n=1$. Here is a counterexample for $n=2$: the variety in $\Bbb{A}^2\times\Bbb{A}^2$ with equation
$$
x_1^2y_1-x_2^2y_2=0
$$
is irreducible; yet, the fibers of the projection to the first factor (obtained by fixing the values of $y_1$ and $y_2$) are all reducible. You can take the projective closure to extend this to $\Bbb{P}^2\times\Bbb{P}^2$.


text:
Q: What does it mean when an array is used to index an array in python? I have a snippit of code as follows:
    y = np.array(self.unique_y)
    random_indices = self.random_generator.integers(0,len(self.unique_y), size=5)
    return y[random_indices]

unique_y is simply an 1D array of [0 1 2].
My understanding of integers is that it produces an array, which is confirmed when I printed y and random_indices.
Here, y is [0 1 2] and random_indices is [2 2 1 0 2].
The return is also [2 2 1 0 2]
My two questions:

*

*Can I just do

    return np.array(self.random_generator.integers(0,len(self.unique_y), size=5))

*What is it doing using random_indices to index y in y[random_indices]?  Both y and random_indices are arrays but one is used to index the other.

A: Make a 1d array:
In [337]: y = np.arange(10)*10
In [338]: y
Out[338]: array([ 0, 10, 20, 30, 40, 50, 60, 70, 80, 90])

and other array with values in the correct range (0 to 10):
In [339]: idx = np.array([2,5,0])

Simply select the corresponding elements from y:
In [340]: y[idx]
Out[340]: array([20, 50,  0])

That works if idx is a list as well.
Things become more complicated when y has more dimensions, and we use arrays to index all dimensions.  For that you need to understand broadcasting.  But for 1d arrays, the indexing is straightforward.
The list equivalent is:
In [341]: [y[i] for i in idx]
Out[341]: [20, 50, 0]


text:
Q: For every row of a dataframe, loop over a list of names I may have bit off more than I could chew at work... But theres no going back for me now...
So I have two tables:
Table 1: Tasks need to be assigned & list of eligible agents

tasks
names

taskA
[susan, mike, bob, ann]

taskB
[susan, david, pat]

......

Table 2: Workload of each agent

name
assigned_task_count

bob
3

ann
2

susan
6

......

For each unassigned task, I want to loop over the qualified agents that can take on this task, find the agent with the least task count, then assign this task to them. This should update Table 2 with +1 on their 'assigned_task_count'.
I'm not trained in Python, only learned on the job. So my foundations are pretty weak.. (and it's come to bite me in the ass..) Please help me save my job...
!!! Editing my question for clarity !!!
Ultimately, I want two tables. One that documents the task and assigned agent && one that tells me the new task per rep.

A: import pandas as pd

df1 = pd.DataFrame({'tasks':['a', 'b'], 'names':[['susan', 'mike', 'bob', 'ann'], ['susan', 'david', 'pat']]})
df2 = pd.DataFrame({'name':['bob', 'ann', 'susan'], 'assigned_task_count':[3,2,6]})

def assign_task(df1, df2):
    df1 = df1.copy()
    assigned_to = []
    df2 = df2.set_index('name')
    for name in df1['names']:
        qualified_agents = df2.index[df2.index.isin(name)]
        agent = qualified_agents[df2.loc[qualified_agents, 'assigned_task_count'].argmin()]
        df2.loc[agent] += 1
        assigned_to.append(agent)
    df2 = df2.reset_index()
    df1['assigned_to'] = assigned_to
    return df1, df2


text:
Q: Xcode: Custom fonts are not supported in glance or notification interfaces Despite the fact that I can set a custom font to a label from Interface Builder and the label even appears with that font when I launch the app on the Apple Watch simulator, Xcode constantly warns me that

Custom fonts are not supported in glance or notification interfaces

Is it just another glitch of Xcode 6.3 or I should not use custom fonts on glances and notification interfaces?

A: For others who might be interested: there is a bug/known issue with IB on XCode 3.x with non-standard fonts and Interface Builder. Custom fonts generally need to be set programatically (via [UIFont fontWithName...)

A: It's not a glitch. Custom fonts are genuinely not supported anywhere except your main WatchKit app.


text: Q: Disciplining dunce hats I'm wondering if anyone has a copy of a preprint by Charles Giffen from 1977, with the enjoyable title, Disciplining dunce hats in 4-manifolds.  I've seen it referred to in various places, including the book, "Embeddings in Manifolds,", by Robert J. Daverman and Gerard Venema. That book explains at least some of the contents (which have to do with spines of 4-manifolds) but I'd be interested in seeing the original paper.


text:
Q: Can I have separate gradle.properties for CI and AndroidStudio? Currently, I have one gradle.properties file. It configured specifically for CI with low available memory, because otherwise CI will crash
org.gradle.jvmargs=-Xmx1500m -XX:MaxPermSize=512m

However, when I make builds on the local machine it is very slow and local machine allows more memory use. Can I have separate gradle.properties for CI and AndroidStudio?

A: According to the documentation, you can have multiple gradle.properties files. One in your project directory and one in user home directory.
As it's said:

The configuration is applied in following order (if an option is configured in multiple locations the last one wins):

*

*from gradle.properties in project build dir.

*from gradle.properties in gradle user home.

In your case, you cam place CI-specific properties into the gradle.properties under user home on CI-server. This properties will be specific for CI-server and take over local properties stored under VCS.


text:
Q: Delphi get components in loop I have pagecontrol with 3 pages. On each page I have control for example TEdit with name's edt1 (on first page),etd2 (on second page),edt3 (on third page).
I want to iterate  for each and set a text value.
Something like :
 for j := 0 to pages.count-1 do
begin
edt[j].text:= 'something ' + IntToStr(j);
end;

but it doesn't work this way

A: This should work:
for i := 0 to pages.Count - 1 do
begin
    TEdit(FindComponent('edt' + IntToStr(i))).Text := 'something';
end;

You should add some error-checking, in case FindComponent returns nil.


text:
Q: Product image don't show other image Hi have a problem , i want to replicate the effect of this website :
http://riviera.sale/collections/flip-flop-collections
I have do all right except for the possibility to change photo ( 1 / 2 / 3 / 4 ) !!
This is my work at moment :
http://www.riviera-umirei.it/swimming.html
Someone could help me?
this is my HTML code :

and this is the HTML code of the store :

        Images

             /

                1

             /

                2

             /

                3

             /

                4

Sorry the snippet is not complete, if is a problem i could try to complete it

A: Go to the director img/shopify.png and search for image shopify.png, you image size is 0 byte which mean it is corrupted. Replace it with new one.


text:
Q: How do I scroll in tmux? How do I scroll with either the keyboard or mouse? The tmux man page indicates one must enter copy-mode to scroll. Is there a way to quickly scroll without manually entering copy-mode?

A: For the newest tmux 2.1, to scroll with your mouse sanely, this is the right answer:
set -g mouse on
# sane scrolling:
bind -n WheelUpPane if-shell -F -t = "#{mouse_any_flag}" "send-keys -M" "if -Ft= '#{pane_in_mode}' 'send-keys -M' 'copy-mode -e; send-keys -M'"

it's not enough to just reload your .tmux.conf you need to restart your tmux, e.g. tmux kill-server && tmux or just quit the services that are using tmux.
taken from https://github.com/tmux/tmux/issues/145

A: Well, you should consider the proper way to set scrolling:
add in your ~/.tmux.conf
set -g mouse on        #For tmux version 2.1 and up

or
set -g mode-mouse on   #For tmux versions < 2.1

It worked for me in windows and panes. Now tmux is just perfect.
Practical tmux has more info on tmux.conf files.

A: In my case, just opt + UpArrow and opt + DownArrow on OSX.

A: Ctrl-b then [ then you can use your normal navigation keys to scroll around (eg. Up Arrow or PgDn). Press q to quit scroll mode.
Alternatively you can press Ctrl-b PgUp to go directly into copy mode and scroll one page up (which is what it sounds like you will want most of the time)
In vi mode (see below), you can also scroll the page up/down line by line using Shift-k and Shift-j (if you're already in scroll mode). Unshifted, the cursor moves instead of the page.
Excerpts from the man page:

tmux may be controlled from an attached client by using a key combination of a prefix key, 'C-b' (Ctrl-b) by default, followed by a command key.

 The default command key bindings are:

[           Enter copy mode to copy text or view the history.

Function                     vi              emacs
--------                     --              -----
Half page down               C-d             M-Down
Half page up                 C-u             M-Up
Next page                    C-f             Page down
Previous page                C-b             Page up
Scroll down                  C-Down or C-e   C-Down
Scroll up                    C-Up or C-y     C-Up
Search again                 n               n
Search again in reverse      N               N
Search backward              ?               C-r
Search forward               /               C-s

Plus a bunch more. Note that you have to press C-b twice if you use that for page up since C-b is bound as the command key. See the man page for information on prefacing a copy mode command with a repeat count.
You can set the key binding mode using Ctrl-b, then
:set-window-option mode-keys emacs

or vi.

A: From my .tmux.conf:
# Sane scrolling
set -g terminal-overrides 'xterm*:smcup@:rmcup@'

This enables native xterm scrolling.

A: This is the way I made it work, and the reasons why I think it is better than the default way.
To try it out, put all the code sections in ~/.tmux.conf.
Step 1. Change the prefix key so you won't have to reach one bit. 'B' is seemingly a close key, but it is in the middle of the two index fingers (at 'F' and 'J', respectively). Because that shortcut is essential in tmux, C-j is much better as it involves zero hand movement (apart from hitting the key).
set -g prefix C-j
unbind C-b
bind C-j send-prefix

Step 2. 'S' (to enter copy-mode) is: 1) close (same reason as above), 2) involves the other hand (compare: the 1-2 in boxing, or the ls command to view files in a directory), and 3) could be thought of as mnemonic for "scroll" (although the copy-mode isn't just about scrolling).
bind s copy-mode

Step 3. The last part, the actual scrolling. 'P' and 'N' are familiar for this purpose to the Emacs users. They are close, intuitive ('P' is above 'N' on the keyboard), and mnemonic ("previous" and "next"). If you just did some scrolling in Emacs, and then go to tmux, it makes sense to have those shortcuts.
However, I found that 'I' and 'K' are even better - they are even closer than 'P' and 'N', and intuitive (for the same reason); as for mnemonics - as scrolling is such a common thing to do, mnemonics won't really matter as the shortcuts will soon bypass your brain and enter the muscle memory.
bind -t emacs-copy 'p' scroll-up
bind -t emacs-copy 'n' scroll-down
bind -t emacs-copy 'i' scroll-up
bind -t emacs-copy 'k' scroll-down

A: This worked for me:
vim ~/.tmux.conf
set -g mode-mouse on      ###Insert this setting with vim, then source the file.
tmux source-file ~/.tmux.conf

A: I'd recommend giving a try to the tmux-better-mouse-mode plugin to solve most of your tmux mouse related issues.
It's compatible with Tmux 2.1+ and the new set-option -g mouse on approach.

A: The only thing that works for me is putting the following in ~/.tmux.conf
# Allow xterm titles in terminal window, terminal scrolling with scrollbar, and setting overrides of C-Up, C-Down, C-Left, C-Right
set -g terminal-overrides "xterm*:XT:smcup@:rmcup@:kUP5=\eOA:kDN5=\eOB:kLFT5=\eOD:kRIT5=\eOC"

(you may need to reboot for this to take effect)
Update:
I found that if you change the setting in Putty Connection > Data > Terminal-type to "putty" (used to fix some formatting issues) from "xterm" then this solution stops working.
Update 2:
Use this if you want "putty" as your terminal type: set -g terminal-overrides "putty*:XT:smcup@:rmcup@:kUP5=\eOA:kDN5=\eOB:kLFT5=\eOD:kRIT5=\eOC"

A: I searched around a lot for this and the best solution for me works as mentioned in this detailed guide:
http://tangledhelix.com/blog/2012/07/16/tmux-and-mouse-mode/
Add these bindings in ~/.tmux.conf:
set -g mode-mouse on

unbind +
bind + \
  new-window -d -n tmux-zoom 'clear && echo TMUX ZOOM && read' \;\
  swap-pane -s tmux-zoom.0 \;\
  select-window -t tmux-zoom

unbind -
bind - \
  last-window \;\
  swap-pane -s tmux-zoom.0 \;\
  kill-window -t tmux-zoom

With the above approach implemented, you can copy from panes in a window as well by zooming into each pane first using Prefix +.
One important detail that was missing with the mouse mode is to press Shift before selecting an area to copy. This will copy it to traditional terminal buffer instead of the tmux copy buffer. (https://wiki.archlinux.org/index.php/Tmux#Scrolling_issues)

A: On OSX Mojave and newer, after entering copy mode with ctrl + b [, you can do:

*

*up arrow for line up

*down arrow for line down

*fn + up arrow for page up

*fn + down arrow for page down

*q to quit copy mode

A: The top answers already explain how to scroll. I'd like to add an option to avoid the need for scrolling: Pipe the output of long commands into less. less is a program to navigate through text files.
superlongcommand | less
Then you can use vim-like bindings (d/u) or PgUp/PgDn to scroll and q to exit. See Less Cheatsheet

A: Host + [
mine key is Ctrl + a
the default key is Ctrl + b
after that its easy to navigate with vim config

A: The answers above did not work for me to enable keyboard scrolling, but this answer from a different question worked:
bind -n Pageup copy-mode -u
bind -n S-Pageup copy-mode -u
bind -n S-Pagedown send-keys Pagedown

A: *

*Ctrl + A - to start scrolling

*Ctrl + C - to stop scrolling


text:
Q: winform C# DataGridView How to Update Columns bound to Generic List Currently I have a DataGridView that is bound to a Generic List. So I have:
dataGridView1.DataSource = ProductBO.GetProducts();

This displays about 300 products and need the ability to update the price and quantity columns when needed. Whats the easiest/cleanest way? There must be some event like to use txtPrice_AfterUpdate() that can be used. Coming from a Webform backgraound and MS Access Im not sure the route to take here. Thanks in advance.

A: Unless it's a really expensive operation you could just refresh the DataSource, literally call that code again.
public void RefreshProducts()
{
    dataGridView1.DataSource = ProductBO.GetProducts();
}


text:
Q: Iterate over array in Ember Handlebars each I have an object that I'm already iterating over to display the content in a template using handlebars {{#each}} - however, within each object there is an array that I also need to loop over.
Need to achieve something like.
{{#each item}}

  {{title}}
  {{rating}}

  {{#each array_field}}
    {{field}}
    {{anotherField}}
  {{/each}}

{{/each}}

A: You can create a pointer var to the current item, then query your array property:
{{#each item in controller}}
  {{item.title}}
  {{item.rating}}

  {{#each otherItem in item.arrayField}}
    {{otherItem.field}}
  {{/each}}

{{/each}}


text:
Q: digest('hex') function not found using CryptoJS I am using crypto-js.js and creating a sha512 function there for creating a variable hash1. we are successfully creating the hash and then updating hash with password but after that not able to use digest function.
var sha512 = function (password, salt) {

    var hash1 = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA512, salt); /** Hashing algorithm sha512 */

    hash1.update(password);

    var value = hash1.digest('hex');
    return {
        salt: salt,
        passwordHash: value
    };
};

Does anybody know how to fix this?

A: digest is an HMAC method in the Node.js crypto module.  The equivalent method in CryptoJS is finalize.  The result of finalize is a CryptoJS WordArray object.  To get a hex string, use the WordArray in a context where it will be treated as a string.  Specifically, replace your:
    var value = hash1.digest('hex');

with:
    var value = '' + hash1.finalize();


text:
Q: what is the problem of this if statement block? I have written this console-app as an exercise, but bumped into a problem with one of the if statements. I can't understand where the problem is, could somebody help me with this?
It wouldn't arrange alphabetically the bold section I mean s3, s1, s2
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv) {
    string s1, s2, s3;
    cout << "Please enter three words: ";
    cin >> s1;
    cin >> s2;
    cin >> s3;

    if(s1.compare(s2)<0)
    {
        if(s2.compare(s3)<0)
        {
            cout << s1 << ", " << s2 << ", " << s3 << endl;
        }
        else
            cout << s1 << ", " << s3 << ", " << s2 << endl;
    }
    else if (s2.compare(s3)<0)
    {
        if(s1.compare(s3)<0)
        {
            cout << s2 << ", " << s1 << ", " << s3 << endl;
        }
        else
            cout << s2 << ", " << s3 << ", " << s1 << endl;
    }
    else if(s3.compare(s2)<0)
    {
        if(s1.compare(s2)<0) // <-- HERE!!
        {
            cout << s3 << ", " << s1 << ", " << s2 << endl;
        }
        else
            cout << s3 << ", " << s2 << ", " << s1 << endl;
    }
    return 0;
}

A: I did some error checking with your code and found out something interesting.
When the order should be S3, S1, S2 the first if statement is still true. You can fix this by using an and statement such as the following:
if ((s1.compare(s2) < 0) && (s1.compare(s3) < 0))
{
... code here ...
}

This additional code in your if statements will keep errors from happening.
I hope this helps!
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv) {
    string s1, s2, s3;
    cout<<"Please enter three words: ";
    cin>>s1;
    cin>>s2;
    cin>>s3;
    if((s1.compare(s2)<0) && (s1.compare(s3)<0))
    {
        if(s2.compare(s3)<0)
        {
            cout<<s1<<", "<<s2<<", "<<s3<<endl;
        }
        else
        cout<<s1<<", "<<s3<<", "<<s2<<endl;
    }
    else if ((s2.compare(s3)<0) && (s2.compare(s1)<0))
    {
        if(s1.compare(s3)<0)
        {
            cout<<s2<<", "<<s1<<", "<<s3<<endl;
        }
        else
        cout<<s2<<", "<<s3<<", "<<s1<<endl;
    }

    else if((s3.compare(s2)<0) && (s3.compare(s1)<0))
    {
        if(s1.compare(s2)<0)
        {
            cout<<s3<<", "<<s1<<", "<<s2<<endl;
        }
        else
        cout<<s3<<", "<<s2<<", "<<s1<<endl;
    }
    return 0;
}

A: Your very first if condition is:
if(s1.compare(s2)<0)

This means it cannot get to the if statement labelled 'HERE', because it will have always taken the first branch.

A: The problem is much earlier than 'HERE'.
This part
if(s1.compare(s2)<0)
{
    if(s2.compare(s3)<0)
    {
        cout << s1 << ", " << s2 << ", " << s3 << endl;
    }
    else
        cout << s1 << ", " << s3 << ", " << s2 << endl;
}

first tests that s1 is 'less than' s2. So you have a partial order s1, s2.
But then you need to find out in which of three possible places the s3 should go: in front of s1, past the s2, of possibly between them. However, the internal conditional allows only two different outputs...
Added:
You can solve the problem starting from the comment above: comparing two elements is enough to sort them. Then you need to compare the third one to both of those to decide if it should go first, second or last:
if(s1.compare(s2) <= 0)       // s1 goes before s2
{
    if(s3.compare(s1) <= 0)       // s3 goes before s1
        cout << s3 << ", " << s1 << ", " << s2 << endl;
    else if(s3.compare(s2) <= 0)  // s3 goes before s2 but after s1
        cout << s1 << ", " << s3 << ", " << s2 << endl;
    else                          // s3 goes after s2
        cout << s1 << ", " << s2 << ", " << s3 << endl;
}
else                          // s2 goes before s1
{
    if(s3.compare(s2) <= 0)       // s3 goes before s2
        cout << s3 << ", " << s2 << ", " << s1 << endl;
    else if(s3.compare(s1) <= 0)  // s3 goes before s1 but after s2
        cout << s2 << ", " << s3 << ", " << s1 << endl;
    else                          // s3 goes after s1
        cout << s2 << ", " << s1 << ", " << s3 << endl;
}

There are 6 permutations possible for 3 input values, and all of them are available. At each path there are at most 3 comparisions done, which is enough to distinguish each of 6 possible outputs.

A: IMHO the first one should be consistently referenced or patterned by else
#include <iostream>
#include <string>
using namespace std;

int main(int argc, char** argv) {
    string s1, s2, s3;
    cout << "Please enter three words: ";
    cin >> s1 >> s2 >> s3;

    if(s1.compare(s2)<0)
    {
        if(s2.compare(s3)<0)                                    // repeat this pattern
            cout << s1 << ", " << s2 << ", " << s3 << endl;     //

        else if(s2.compare(s3) == 0)                            //
            cout << s1 << ", " << s2 << " = " << s3 << endl;    //

        else
            cout << s1 << ", " << s3 << ", " << s2 << endl;     //
    }                                                           //
    else if (s2.compare(s3)<0)
    {
        if(s3.compare(s1)<0)
            cout << s2 << ", " << s3 << ", " << s1 << endl;

        else if(s1.compare(s3) == 0)
            cout << s2 << ", " << s1 << " = " << s3 << endl;
        else
            cout << s2 << ", " << s1 << ", " << s3 << endl;
    }
    else if(s1.compare(s3)<0)
    {
        if(s3.compare(s2)<0) // <-- HERE!!

            cout << s1 << ", " << s3 << ", " << s2 << endl;

        else if(s2.compare(s3) == 0)
            cout << s1 << ", " << s2 << " = " << s3 << endl;
        else
            cout << s1 << ", " << s2 << ", " << s3 << endl;
    }
    return 0;
}


text:
Q: Why find command failing from make file I am working on modifying a windows make file. The file, which is part of legacy build code has the following lines --
    WROOT := "MyBuild/win/Program Files/Windows Kits/10"

   ROOT_SDK_Version := $(shell find $(WROOT_WIN10_SDK)/Include -maxdepth 1 -type d -path $(WROOT_WIN10_SDK)/Include/[0-9.]* )

The SHELL variable is mapped to bin/sh but when I print the variable ROOT_SDK_Version, it is empty. However, when I manually invoke the find command with the same arguments, it is giving the expected out.
To debug this issue, I modified above line in make file as below
ROOT_SDK_Version := $(shell find $(WROOT_WIN10_SDK)/Include -maxdepth 1 -type d -path $(WROOT_WIN10_SDK)/Include/[0-9.]* 2> output.txt )

And I see the contents of the file output.txt after running make -
find: paths must precede expression
Usage: find [-H] [-L] [-P] [path...] [expression]

So why is the find command failing when running from make file but is successful when I run it manually using the same arguments? Any pointers appreciated.
Providing more context-
WROOT_WIN10_SDK := "$(GOBUILD_CAYMAN_MSVC_DESKTOP_ROOT)/win/Program Files/Windows Kits/10"
The variable GOBUID...is== E:/Myscpetre20/depot/sim/sim-20fq1/build/gobuild/compcache/cayman_msvc_desktop/ob-11144741/windows2016-clean
So WROOT_WIN10_SDK is == "E:/Myscpetre20/depot/sim/sim-20fq1/build/gobuild/compcache/cayman_msvc_desktop/ob-11144741/windows2016-clean/win/Program Files/Windows Kits/10"

A: I think the argument to the -path option needs to be quoted -- otherwise the glob * will be expanded by the shell rather than being passed to find.  So...
   ROOT_SDK_Version := $(shell find $(WROOT_WIN10_SDK)/Include -maxdepth 1 -type d -path '$(WROOT_WIN10_SDK)/Include/[0-9.]*' )


text:
Q: Adding to arrays and finding values in arrays I have 2 arrays:  one that has values to search a document for (arr) and one that will put in associated cell addresses with the found values (arr2).  I have no issues with arr, and have used it earlier in my code successfully.
With arr2, I want to find any cells that contain the values in arr, and add the cell address lRow amount of rows down from it to arr2, but ONLY if that address isn't already in arr2.
I found 2 SO answers that I'm trying to combine in order to solve my issue, but so far with no luck.
Excel VBA - adding an element to the end of an array
How to search for string in an array
My code below:
Sub Initiate()

Dim arr(3) As Variant
    arr(0) = "Value1"
    arr(1) = "Value2"
    arr(2) = "Value3"
    arr(3) = "Value4"
Dim arr2() As Variant
Dim Alc as String
Dim lRow as Long
Dim fVal as String

lRow = Activesheet.Cells(Activesheet.Rows.Count, 1).End(xlUp).Row

For Each element In arr

fVal = element

Set fRange = WA.Cells.Find(What:=fVal, LookIn:=xlFormulas _
    , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

While Not fRange Is Nothing

    While Not IsInArray(fRange.Offset(lRow - 6, 0).Address(False, False), arr2)

        ReDim Preserve arr2(0 To UBound(arr2) + 1) As Variant

        arr2(UBound(arr2)) = fRange.Offset(lRow - 6, 0).Address(False, False)

    Set fRange = WA.Cells.Find(What:=fVal, LookIn:=xlFormulas _
    , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

    Wend

Wend

Next element

Alc = "="

    For Each element In arr2

        Alc = Alc & element & "+"

    Next element

Alc = Left(Alc, Len(Alc) - 1)

MsgBox Alc

End Sub

Function IsInArray(stringToBeFound As String, arr2 As Variant) As Boolean

    IsInArray = (UBound(Filter(arr2, stringToBeFound)) > -1)

End Function

When run I get the following error:

On this line of code (within the IsInArray function):
IsInArray = (UBound(Filter(arr2, stringToBeFound)) > -1)
Any help is greatly appreciated!

A: I don't like using Filter because it also matches on substrings, and often that's not what you want
Function IsInArray(stringToBeFound As String, arr2 As Variant) As Boolean

    IsInArray = Not IsError(Application.Match(stringToBeFound, arr2, 0))

End Function

Also:
ReDim Preserve arr2(0 To UBound(arr2) + 1) As Variant

should probably be:
ReDim Preserve arr2(0 To UBound(arr2) + 1)

A: I figured I'd add in my comment here as an answer. (I hope it's not outside the scope of this question/forum). If you're looking to store unique values in a collection, I'm not sure that you can beat the performance of a dictionary.
Outside of the loop, you would declare and instantiate the Dictionary:
Dim oDict as Object
Set oDict = CreateObject("Scripting.Dictionary")

The code that you currently use to search arr2 then add the value if unique would be amended to look something like:
If Not oDict.Exists(fRange.Offset(lRow - 6), 0).Address(False, False)) then
    oDict(fRange.Offset(lRow - 6), 0).Address(False, False)) = ""
End If

Set fRange = WA.Cells.Find(What:=fVal, LookIn:=xlFormulas _
, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)

I don't know how many records you expect to be inserting or searching through, or how performant your software needs to be, but performance can be significantly different.


text:
Q: X86_64 call convention issue As we know, X86_64 use register rdi, rsi, rdx, rcx, r8, r9 to store normal function's arguments, and use stack memory to store large argument, and use xmm to store float and double argument. But in my code, the function 'myuprobe_sum_dww_ptr' is wired. It doesn't use rdi to store the first argument but to store a local variable. Please see the code below, and I have commented the register usage information in the code. Could anyone help to explain?
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
struct double_wraper
{
    double data;
};
struct double_wraper_wraper
{
    double_wraper_wraper()
    {
        dp = new double_wraper();
    }
    ~double_wraper_wraper()
    {
        delete dp;
    }
    uint32_t a;
    struct double_wraper d;
    struct double_wraper* dp;
};

// a -> rdi, b -> rsi
uint32_t myuprobe_sum_int(uint32_t a, uint32_t b)
{
    //printf("%u + %u = %u, addr = %p\n", a, b, &a);
    return a + b;
}

// d1 -> rsi, d2 -> rdx, v -> rcx
double_wraper_wraper myuprobe_sum_dww_ptr(const double_wraper_wraper* d1, const double_wraper_wraper* d2, uint32_t v)
{
    double_wraper_wraper d3; // d3 -> rdi, why??????????????
    d3.a = d1->a + d2->a + v;
    d3.d.data = d1->d.data + d2->d.data;
    d3.dp->data = d1->dp->data + d2->dp->data;
    //printf("%u + %u = %u, addr = %p\n", d1->a, d2->a, d3.a, d1);
    //printf("%lf + %lf = %lf, addr = %p\n", d1->d.data, d2->d.data, d3.d.data, d1);
    printf("%lf + %lf = %lf, addr = %p\n", d1->dp->data, d2->dp->data, d3.dp->data, d1);
    return d3;
}

// d1 -> rdi, d2 -> rsi, d3 -> rdx, v -> rcx
double_wraper myuprobe_sum_dw_ptr(const double_wraper* d1, const double_wraper* d2, const double_wraper_wraper* d3, uint32_t v)
{
    double_wraper d4;
    d4.data = d1->data + d2->data + d3->d.data;
    //printf("%lf + %lf + %lf = %lf, addr = %p\n", d1->data, d2->data, d3->d.data, d4.data, d1);
    return d4;
}

int main()
{
    while(1) {
        double_wraper_wraper d4, d5;
        d4.a = rand();
        d4.d.data = rand() + (double)rand() / RAND_MAX;
        d4.dp->data = rand() + (double)rand() / RAND_MAX;
        d5.a = rand();
        d5.d.data = rand() + (double)rand() / RAND_MAX;
        d5.dp->data = rand() + (double)rand() / RAND_MAX;
        auto d7 = myuprobe_sum_dww_ptr(&d4, &d5, 100);
        uint32_t a,b;
        a = rand();
        b = rand();
        auto c = myuprobe_sum_int(a, b);

        double_wraper d8,d9;
        d8.data = rand() + (double)rand() / RAND_MAX;
        d9.data = rand() + (double)rand() / RAND_MAX;
        auto d10 = myuprobe_sum_dw_ptr(&d8, &d9, &d4, 100);
        usleep(5000000);
    }
}

Compile: g++ test.cpp -o test -g -O0


text:
Q: Sending my AS3 AIR application window in front of everything I tried searching for this but nothing worked.
I'm trying to make my AIR application window to be always visible on top of every other windows.
I read about alwaysInFront, but I can't get it to work.
I am using an AS3 Class file on AIR 20.0 for Desktop.
My code looked like this:
I imported flash.desktop.NativeApplication; and in the first function I added windowObj.alwaysInFront = true;.
It did not work, saying windowObj is not a thing. How do I do this?
Thanks for your help!

A: Try:
this.nativeWindow.alwaysInFront = true;


text:
Q: How to add new json field to existing json in groovy My existing Json looks like:
def json_req = "{\"date\":\"Tue, 06 Oct 2015 09:10:52 GMT\",\"nonce\":\"6cm7PmwDOKs\",\"devId\":\"<value>\",\"appId\":\"<value>\"}

Perform the operation I can get sig field with value. I need to append this additional field with value as below:
"sig":"<value>"

So that the new json looks like:
def json_req = "{\"date\":\"Tue, 06 Oct 2015 09:10:52 GMT\",\"nonce\":\"6cm7PmwDOKs\",\"devId\":\"<value>\",\"appId\":\"<value>\",\"sig\":\"<value>\"}"

Within the same script can I append this new parameter with the value in json?

A: You can parse the json with JsonSlurper, and since the result of that is a LazyMap, you can simply add the new entry to it (lines with println added as hints):
import groovy.json.*

def json_req = '''{
"date":"Tue, 06 Oct 2015 09:10:52 GMT",
"nonce":"6cm7PmwDOKs",
"devId":"<value>",
"appId": "<value>"
}'''

def json = new JsonSlurper().parseText(json_req)
println json.getClass().getName()
json << [sig: "<value>"] // json.put('sig', '<value>')
println JsonOutput.toJson(json)

Try it on the groovy web console


text:
Q: Error updating fields in SQL Server front end application I am working on an application which is nearly complete except for my one page.
On the page is a gridview which is showing data from a database which works, the problem is when the user tries to update the information it is throwing out errors.
This is my code - can someone see what I am doing wrong and how I can solve this problem?
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
    GridViewRow row = GridView1.Rows[e.RowIndex];

    int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    int Period_Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    int Evo_StockLink = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

    string Evo_ItemCode = (row.Cells[4].Controls[0] as TextBox).Text;
    string Evo_Description = (row.Cells[5].Controls[0] as TextBox).Text;

    float UnitRate = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    float MinRate = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    float RateBeforeSevenDays  = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
    float RateAfterSevenDays = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("UPDATE rates SET Period_Id = @Period_Id, Evo_StockLink = @Evo_StockLink, Evo_ItemCode = @Evo_ItemCode, Evo_Description = @Evo_Description, MinRate = @MinRate, RateBeforeSevenDays = @RateBeforeSevenDays, RateAfterSevenDays = @RateAfterSevenDays  WHERE Id = @Id"))
        {
            cmd.Parameters.AddWithValue("@Id", Id);
            cmd.Parameters.AddWithValue("@Period_Id", Period_Id);
            cmd.Parameters.AddWithValue("@Evo_StockLink", Evo_StockLink);
            cmd.Parameters.AddWithValue("@Evo_ItemCode", Evo_ItemCode);
            cmd.Parameters.AddWithValue("@Evo_Description", Evo_Description);
            cmd.Parameters.AddWithValue("@UnitRate", UnitRate);
            cmd.Parameters.AddWithValue("@MinRate", MinRate);
            cmd.Parameters.AddWithValue("@RateBeforeSevenDays", RateBeforeSevenDays);
            cmd.Parameters.AddWithValue("@RateAfterSevenDays", RateAfterSevenDays);

            cmd.Connection = con;
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }

    GridView1.EditIndex = -1;
    this.BindGrid();
}

The error shown is :

Index was out of range. Must be non-negative and less than the size of the collection.
  Parameter name: index
Exception Details: System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
  Parameter name: index
Source Error:
Line 61:         {
  Line 62:             GridViewRow row = GridView1.Rows[e.RowIndex];
  Line 63:             int Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
  Line 64:             int Period_Id = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
  Line 65:             int Evo_StockLink = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);

A: In the aspx ensure you have the DataKeyNames = "Id", you also passing all the fields using Datakeys this will update the entire DB to that value.


text:
Q: MasterDetailPage shows a blank page My PCL starts in MyProject.Views.MainPage, and this is its source code:
<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyProject.Views.MainPage">
    <Label Text="Hello"/>
<MasterDetailPage.Master>
    <ContentPage>
        <ContentPage.Content BackgroundColor="Gray" Title="MasterPage">
            <StackLayout Margin="5, 30, 5, 5">
                <Label Text="Master page"/>
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>
</MasterDetailPage.Master>

<MasterDetailPage.Detail>
    <ContentPage Padding="10">
        <ContentPage.Content>
            <StackLayout Margin="5, 30, 5, 5">
                <Label Text="Detail page"/>
            </StackLayout>
        </ContentPage.Content>
    </ContentPage>
</MasterDetailPage.Detail>

I have no warnings and no errors, but when I execute the application, I only see a blank page.

A: I have found two errors:

*

*You need to close the MasterDetailPage tag at the end of the code

*BackgroundColor="Gray" Title="MasterPage" these properties are availables in the ContentPage and you are using them inside other property (ContentPage.Content)

So if you make these changes you will get something similar to this:
<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage
    x:Class="Test.Pages.MasterDetailPage1"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
    <Label Text="Hello" />
    <MasterDetailPage.Master>
        <ContentPage Title="Master" BackgroundColor="Gray">
            <StackLayout Margin="5,30,5,5">
                <Label Text="Master page" />
            </StackLayout>
        </ContentPage>
    </MasterDetailPage.Master>

    <MasterDetailPage.Detail>
        <ContentPage Padding="10">
            <ContentPage.Content>
                <StackLayout Margin="5,30,5,5">
                    <Label Text="Detail page" />
                </StackLayout>
            </ContentPage.Content>
        </ContentPage>
    </MasterDetailPage.Detail>
</MasterDetailPage>

I hope this can help you.


text:
Q: Putting If() inside an array() Is it possible to put if statement inside an array like this
array(1 => 1, 2 => 2 if(!empty(3)){echo ", 3 => 3";});

instead of going
if(!empty(3)){
    array (1 => 1, 2 => 2, 3 => 3);
}
else {
    array (1 =>1, 2 => 2);
}

A: You could add the value after you created the array
$array = [1 => 1, 2 => 2];
if (...) {
    $array[3] = 3;
}

if you don't need the key, you could also just write
$array[] = 3;

A: $array = [ 1 => 1, 2 => 2  ];
    if ( !empty(3) ) {
        $array[3] = 3;
    }

A: You can use the conditional operator for value like below
$array = array(
    '1' => '1',
    '2' => '2',
    '3' => $cond ? '3' : ''
);

if you need to add condition in key you can do below way
if ($cond) {
    $array[3] = 3;
}

you can also use array union operator or array_merge:
array('1' => '1') + ($cond ? array('3' => '3') : array())
array_merge(array('1' => '1'), $cond ? array('3' => '3') : array())

now you have to decide what is better for you.


text:
Q: Cordova app cannot use internet after downloading via Play Store Published a new app yesterday on Play Store been using/testing the app for months without a problem now but the version downloaded from the play store cannot access the internet (assumption). Never had this issue while running the app from Cordova CLI.
The app has a login page at launch which connects to a server - I can see in the app settings the app hasn't used any data at all and no errors are thrown in the app or the log cat (adb logcat).
What could be the problem? Details as follows;
Tested Devices

*

*HTC10 (Android 7.0)

*Google Pixel  (Android 7.1.2)

Config.xml
<access origin="*" />
Manifest
<uses-sdk android:minSdkVersion="16" android:targetSdkVersion="25" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE" />
<uses-permission android:name="${applicationId}.permission.PushHandlerActivity" />
<permission android:name="${applicationId}.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<permission android:name="${applicationId}.permission.PushHandlerActivity" android:protectionLevel="signature" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

CSP
<meta http-equiv="Content-Security-Policy" content="default-src * gap://ready; connect-src * ws: wss:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; img-src 'self' data: *">

Auth Model
 login: function(un, pw, onProgress, onSuccess, onAbort, onError) {
    var params = {
        username: un,
        password: pw,
    };

    var httpHeaders = {
        'X-CSRF-Token': app.token
    };

    app.authRemote.restClient.call(config.serverURL + '/' + config.serviceEndPoint + '/endpoint/login', JSON.stringify(params), {requestMethod: 'POST', requestDataType: 'application/json', httpHeaders: httpHeaders, responseDataType: 'json'},
        function _onProgress() {
            onProgress(app.authRemote.restClient);
        },
        function _onSuccess(result) {
            onSuccess(result);
        },
        function _onAbort() {
            onAbort();
        },
        function _onError(error) {
            onError(error);
        }
    );
},

Auth Controller
this.login = function(username, password, onSuccess, onError){
    app.authRemote.login(username, password,
        function _onProgress(restClient) {
            console.log('Sent = ' + restClient.bytesSent + ' | received = ' + restClient.bytesReceived);
        },
        function _onSuccess(data) {
            onSuccess(data);
        },
        function _onAbort() {
        },
        function _onError(error) {

            onError(error);
        }
    );
};

Console from logcat
 07-14 11:03:52.092 18738 18738 D SystemWebChromeClient: file:///android_asset/www/js/modules/system/controllers/auth-controller.js: Line 670 : Sent = 0 Bytes | received = 0 Bytes

A: Actually found the answer to this finally...
Ajax requests were being blocked to HTTPS because I'm using a self-signed SSL certificate.
Although it is not recommended to do this (you should use a valid certificate for production), here is a quick way around;

*

*Install the cordova-plugin-certificates plugin

*cordova.plugins.certificates.trustUnsecureCerts(true); before making requests


text:
Q: Memory usage of matrix object reported in RStudio Suppose I have a large matrix x of type numeric with 1e4 * 1e4 elements.
x should require 1e8 * 8/ 1e6 = 800MB memory (plus some header). This is confirmed by object.size() and pryr::object_size():
> x <- matrix(NA_real_, nrow = 1e4, ncol = 1e4)
> object.size(x)
800000216 bytes
> pryr::object_size(x)
800 MB

However, size reported in the 'environment' tab is 762.9MB.
How does RStudio calculate memory usage of objects reported in the 'environment' tab of RStudio and where does the difference come from?

A: RStudio shows you the same memory size as object.size. A MB contains 1024KB and a KB contains 1024B:
object.size(x)
# 800000216 bytes
object.size(x) / 1024 / 1024
# 762.9 bytes

I tried looking in the pryr::object_size code but it is implemented in C. I took a look in the source code and it looks like the calculation of bytes is like this:
 double bytes = 0;
  // Big vectors always allocated in 8 byte chunks
  if      (n_bytes > 16) bytes = n_bytes * 8;
  // For small vectors, round to sizes allocated in small vector pool
  else if (n_bytes > 8)  bytes = 128;
  else if (n_bytes > 6)  bytes = 64;
  else if (n_bytes > 4)  bytes = 48;
  else if (n_bytes > 2)  bytes = 32;
  else if (n_bytes > 1)  bytes = 16;
  else if (n_bytes > 0)  bytes = 8;

  return bytes;
}

So probably that's why your calculation is for 800MBs which matches pryr.