lundi 31 août 2015

Find all numbers in a integer list that add up to a number

I was asked this question on an interview. Given the following list:

[1,2,5,7,3,10,13]

Find the numbers that add up to 5.

My solution was the following:

#sort the list:
l.sort()
result = ()
for i in range(len(l)):
    for j in range(i, len(l)):
         if l[i] + l[j] > 5:
             break
         elif l[i] + l[j] == 5:
             result += (l[i], l[j])

The idea I presented was to sort the list, then loop and see if the sum is greater than 5. If so, then I can stop the loop. I got the sense the interviewer was dissatisfied with this answer. Can someone suggest a better one for my future reference?



via Chebli Mohamed

Woocommerce Show default variation price

I'm using Woocommerce and product variations and all my variations have a default variation defined. I would like to know, how I can find the default variation and display it's price.

This is the code I got so far, but it displays the cheapest variation price, and I'm looking for my default variation product price instead.

// Use WC 2.0 variable price format, now include sale price strikeout
add_filter( 'woocommerce_variable_sale_price_html', 'wc_wc20_variation_price_format', 10, 2 );
add_filter( 'woocommerce_variable_price_html', 'wc_wc20_variation_price_format', 10, 2 );
function wc_wc20_variation_price_format( $price, $product ) {
// Main Price
$prices = array( $product->get_variation_price( 'min', true ), $product->get_variation_price( 'max', true ) );
$price = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );
// Sale Price
$prices = array( $product->get_variation_regular_price( 'min', true ), $product->get_variation_regular_price( 'max', true ) );
sort( $prices );
$saleprice = $prices[0] !== $prices[1] ? sprintf( __( 'HERE YOUR LANGUAGE: %1$s', 'woocommerce' ), wc_price( $prices[0] ) ) : wc_price( $prices[0] );

if ( $price !== $saleprice ) {
    $price = '<del>' . $saleprice . '</del> <ins>' . $price . '</ins>';
}
return $price;

}

I found the code example here Woocommerce variation product price to show default



via Chebli Mohamed

Powershell parsing regex in text file

I have a text file:

Text.txt

2015-08-31 05:55:54,881 INFO   (ClientThread.java:173) - Login successful for user = Test, client = 123.456.789.100:12345
2015-08-31 05:56:51,354 INFO   (ClientThread.java:325) - Closing connection 123.456.789.100:12345

I would like output to be:

2015-08-31 05:55:54 Login user = Test, client = 123.456.789.100
2015-08-31 05:56:51 Closing connection 123.456.789.100

Code:

$files = Get-Content "Text.txt"
$grep = $files | Select-String "serviceClient:" , "Unregistered" |  
Where {$_ -match '^(\S+)+\s+([^,]+).*?-\s+(\w+).*?(\S+)$' } |
Foreach {"$($matches[1..4])"} | Write-Host

How can I do it with the current code?



via Chebli Mohamed

How to preprocess high cardinality categorical features?

I have a data file which has features of different mobile devices. One column with categorical data type has 1421 distinct types of values. I am trying to train a logistic regression model along with other data that I have. My question is: Will the high cardinality column described above affect the model I am training? If yes, how do I go about preprocessing this column so that it has lower number of distinct values?



via Chebli Mohamed

Meteor cursor counts and forEach

I need to add min and max fields into collection items in publish function and filter items by this fileds. I found the solution by using forEach for cursor:

Meteor.publish 'productsWithMinMax', (filter, options) ->
    Products.find(filter, options).forEach (p) =>
        p.min = Math.min p.price1, p.price2, p.price3, p.price4
        p.max = Math.max p.price1, p.price2, p.price3, p.price4

        if p.min && p.max && (p.max < p.mainPrice || p.min > p.mainPrice )
            @added "products", p._id, p

    Counts.publish @, 'numberOfProductsWithMinMax', Products.find(filter), {noReady: true}

    @ready()

But now Counts.publish returns wrong count for my cursor. How to count my cursor in this case?



via Chebli Mohamed

ES6 Import Folder

Does the ES6 module syntax allow you to import something from a folder?

For example if I have ./sub/main.js and I try import foo from './sub in the ./main.js file, will this work?

Could I get this sort of importing from a folder to work with babel and webpack?

Basically this would be the equivalent of __init__.py in Python.



via Chebli Mohamed

Is there a custom of distributing a key description with databases, like it is done with maps?

For a project with a more complicated relational database structure, one of the requirements is long-term stability of the SQL database. To achieve this, I did some searching for a standard way of describing certain paths through a relational database. For example, this would include a description on how to combine related tables or a hierarchy of the keys/IDs used in the database.

What I am trying to do is a description of the database, so that someone who just imports the database dump to a SQL server will know how what queries to write and what fields to use as keys. (This situation could arise if, for example, the software used with the database can no longer be run at some point in time.)

While I am aware this could be done with UML, I'd like to ask whether there is some sort of standard or custom of distributing databases in open source software with a description, like the key always printed on maps so that people know what each color and line type means. Thanks!



via Chebli Mohamed

Download Google Sheet as CSV and keep numbers values as text

When I download one of my Google Sheets to csv, it removes the proceeding "0" from my values. For example, "0666666" will become "666666". How can I modify the code below so that it keeps that front zeros? Thanks!

def static_tabs():
    static_tabs = ('Locating Media','Schedules')
    for tab in static_tabs:
        edit_ws = edit.worksheet(tab)
        print ("EDIT"+format(edit_ws))
        filename = str(tab) +'.csv' 
        with open('C:/Users/A_DO/Dropbox/2. The Machine/10. Edit and QC Google Doc/Edit/Static Tabs/' + filename, 'wb') as f:
            writer = csv.writer(f,quoting=csv.QUOTE_ALL)
            writer.writerows(edit_ws.get_all_values())

static_tabs()



via Chebli Mohamed

NpmInstallDir parameter not found with MSBuild of Apache Cordova project

I'm using VS2015 to build an Apache Cordova project. This builds fine using the editor itself, however when I run the build using MSBuild:

"C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe" /p:Configuration=Release MySolution.sln"

I encounter the following error:

(InstallMDA target) -> C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\ApacheCordovaTools\vs-mda-targets\Microsoft.MDA.FileMirroring.targets(287,5): error MSB4044: The "RunMdaInstall" task was not given a value for the required parameter "NpmInstallDir".

Opening the Microsoft.MDA.FileMirrorring.targets file, I see the reference to NpmInstallDir. How is this supposed to get set during an MSBuild? (Needless to say, running echo %NpmInstallDir% on my commandline does not return a path, so I don't have this set.)

Doing a search for NpmInstallDir in the directory where my Visual Studio lives, I see that it is retrieved through some arguments. Do I need to pass in a specific argument to MSBuild to locate NpmInstallDir?



via Chebli Mohamed

Pythpn Regex Select Element

I've got an array with elements which are different names such as and

[abc, def, agh § dsd, sdse, 12a § asd].

I would like to select only those that have § in it and erase the other elements from the array.

The names change in length and also the position of § in the name changes]

Does anybody have an idea?

Mine was

    names = [re.findall(r'(?<=>)[^><]+(?=<)', str(i).strip()) for i in select('§')]

However, my regex skills are below zero...so...help is much appreciated!



via Chebli Mohamed

How to set PHPStorm get existed word to autocomplete?

In Sublime Text, when I have helloWorldTesteStringLong written in an open file, it will show in auto complete list, independence if I in their file or not

How to can I set this configuration in PHPStorm? For show written word in autocomplete list



via Chebli Mohamed

Finding and replacing strings with certain character patterns in array

I have a pretty large database with some data listed in this format, mixed up with another bunch of words in the keywords column.

BA 093, RJ 342, ES 324, etc.

The characters themselves always vary but the structure remains the same. I would like to change all of the strings that obey this character structure : 2 characters A-Z, space, 3 characters 0-9 to the following:

BA-093, RJ-342, ES-324, etc.

Be mindful that these strings are mixed up with a bunch of other strings, so I need to isolate them before replacing the empty space.

I have written the beginning of the script that picks up all the data and shows it on the browser to find a solution, but I'm unsure on what to do with my if statement to isolate the strings and replace them.

<?php

require 'includes/connect.php';

$pullkeywords = $db->query("SELECT keywords FROM main");

while ($result = $pullkeywords->fetch_object()) {

    $separatekeywords = explode(" ", $result->keywords);
    print_r ($separatekeywords);
    echo "<br />";
}

Any help is appreciated. Thank you in advance.



via Chebli Mohamed

maven builds fails inside ubuntu vagrant machine as well as docker instance

I am developing an api using jaxb. The maven build (using jdk-7) works on my local windows machine. Now if I try to build it on my vagrant box (ubuntu/trusty64) after setting up maven and openjdk7 on the vm, I get following error on performing mvn clean install:

java.io.FileNotFoundException (operation not permitted)

However, if it is a simple java app, I am able to do perform maven builds on the same machine without error (from http://ift.tt/1COWknQ)

Detailed error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.4:war (default-war) on project '<app>' : Could not copy webapp classes [/usr/src/<app>/target/classes]: /usr/src/<app>/target/<app>-03.00.00.01-SNAPSHOT/WEB-INF/classes/<my-app-src>/rest/config/ResourceConfig.class (Operation not permitted) -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.apache.maven.plugins:maven-war-plugin:2.4:war (default-war) on project <my-app>: Could not copy webapp classes [/vagrant_data/<my-app-src>/<my-app>/target/classes]
[/vagrant_data/<my-app-src>/<my-app>/target/classes]
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:217)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:84)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:59)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.singleThreadedBuild(LifecycleStarter.java:183)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:161)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:320)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:156)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:537)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:196)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:622)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Could not copy webapp classes [/vagrant_data/<my-apps-src>/target/classes]
    at org.apache.maven.plugin.war.packaging.ClassesPackagingTask.performPackaging(ClassesPackagingTask.java:80)
    at org.apache.maven.plugin.war.packaging.WarProjectPackagingTask.handleClassesDirectory(WarProjectPackagingTask.java:207)
    at org.apache.maven.plugin.war.packaging.WarProjectPackagingTask.performPackaging(WarProjectPackagingTask.java:104)
    at org.apache.maven.plugin.war.AbstractWarMojo.buildWebapp(AbstractWarMojo.java:505)
    at org.apache.maven.plugin.war.AbstractWarMojo.buildExplodedWebapp(AbstractWarMojo.java:433)
    at org.apache.maven.plugin.war.WarMojo.performPackaging(WarMojo.java:213)
    at org.apache.maven.plugin.war.WarMojo.execute(WarMojo.java:175)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:101)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:209)
    ... 19 more
Caused by: java.io.FileNotFoundException: /vagrant_data/<my-apps-src>/target/<my-app>-03.00.00.01-SNAPSHOT/WEB-INF/classes/<my-app-src>/rest/config/ResourceConfig.class (Operation not permitted)
    at java.io.FileOutputStream.open(Native Method)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:212)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:160)
    at org.codehaus.plexus.util.FileUtils.doCopyFile(FileUtils.java:1068)
    at org.codehaus.plexus.util.FileUtils.copyFile(FileUtils.java:1049)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFile(AbstractWarPackagingTask.java:334)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask$1.registered(AbstractWarPackagingTask.java:154)
    at org.apache.maven.plugin.war.util.WebappStructure.registerFile(WebappStructure.java:207)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFile(AbstractWarPackagingTask.java:149)
    at org.apache.maven.plugin.war.packaging.AbstractWarPackagingTask.copyFiles(AbstractWarPackagingTask.java:104)
    at org.apache.maven.plugin.war.packaging.ClassesPackagingTask.performPackaging(ClassesPackagingTask.java:75)
    ... 27 more



via Chebli Mohamed

Controlling web application user access to file system

First, a preface: I'm new to Stack Overflow, recently reintroduced to programming, and very new to security, so please go easy on me. I'm hoping someone can point me in the right direction.

We are a large multi-site nonprofit organization with a small programming team supporting an obsolete Administration/Accounting software that was programmed in-house. In the last few years, part of our Human Resources module has been rewritten as an ASP.NET MVC web application (C#, Javascript, HTML) so that remote sites can install it and access employee information. The eventual plan is to move it all to RESTful Web Api, so I'm spending time on Pluralsight learning REST as well as the programming languages referenced above.

Where we've hit a snag is in security. Right now an authorized user in this web application has carte blanche access to data, so we can't make certain sensitive data available until we can employ authorization on a more granular level.

Our most pressing issue is document management. Documents on our old system are saved in a series of folders in .doc or .pdf format. Our web application needs to be able to authenticate a given user, access that same file structure and limit his/her access to only the folders he/she is authorized to view.

I've been searching stackoverflow and the internet, but haven't come across any clearcut information on how to proceed.

I would appreciate any input on strategies you may have used to tackle a similar problem. Thanks in advance for your help!



via Chebli Mohamed

How to dynamically traverse a global array without creating any copy of it?

For example something like this:

function POSTTraverse($key0 [, $key1 [, $key2 ...]]) {
    ...
    return $value;
}

The usage would be for example:

POSTTraverse('document', 'item', 'quantity', 5);



via Chebli Mohamed

XAML Binding: Combobox populating textbox in one scenario, but not another? WPF

I have one set of code working properly. It loads the "address" field from a database of user records containing stuff like [ID, Fname, Lname, address, zip, etc] into a ComboBox's selection set. Once a user selects an address it displays that selection in a corresponding textbox as well.

working code:

<Window x:Class="CC_Ticketing_WPF.MainWindow"
       xmlns:local="clr-namespace:CC_Ticketing_WPF"
       Title="MainWindow">
    <Window.Resources>
        <DataTemplate x:Key="orderheaderTemplate">
            <StackPanel>
                <TextBlock Text="{Binding XPath=address}"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ComboBox x:Name="cb_Address" 
                  DataContext="{StaticResource orderheaderDataSource}" 
                  ItemsSource="{Binding XPath=/dataroot/orderheader/address}"  
                  IsEditable="True"/>
        <TextBlock x:Name="tb_Address" 
                   Text="{Binding ElementName=cb_Address,Path=Text}"/>
    </StackPanel>
</Window>

The problem is I know that's very limited as it relies on defining everything in the stack panel. I am trying this something along these lines instead:

broken code

<Window x:Class="CC_Ticketing_WPF.MainWindow"
        xmlns:local="clr-namespace:CC_Ticketing_WPF"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow">
    <Window.Resources>
        <DataTemplate x:Key="orderheaderTemplate">
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ComboBox x:Name="cb_Address" 
                  DataContext="{StaticResource orderheaderDataSource}" 
                  ItemsSource="{Binding XPath=/dataroot/orderheader}" 
                  DisplayMemberPath="address" 
                  SelectedValuePath="Content" 
                  IsEditable="True"/>
        <TextBlock x:Name="tb_Address" 
                   Text="{Binding ElementName=cb_Address,
                                  Path=SelectedItem.Content,
                                  Mode=OneWay}"/>
    </StackPanel>
</Window>

This loads the addresses and allows selection in the combobox, but sends nothing to the textbox. Eventually I'd want selecting an address from this combox to not only send the selection to the textbox, but also send the other relevant data from that record to other textbox's (like you select just an address and it populates a bunch of textboxes with the address, name, zip, etc.) Pretty common business need. Could someone put me on the right track here to accomplish this?



via Chebli Mohamed

Animate a div sliding with a toggle button

I can't seem to figure out how to animate my div sliding with a toggle button.

I tried using variables but I have multiple of these and I am creating too many variables to keep track of the clicks on each of them.

$(document).ready(function() {
  
  $('#toggle-sidebar').click(function() {
    $('#sidebar').animate({
      left: '200'
    }, 500);
  });
  
});
#sidebar {
  position: absolute;
  top: 0;
  left: 0;
  width: 20em;
  height: 70vh;
  background:#333;
}

#toggle-sidebar {
  float: right;
}
<script src="http://ift.tt/1oMJErh"></script>

<div id="sidebar"></div>

<a href="#" id="toggle-sidebar">Toggle</a>


via Chebli Mohamed

SQL update with sub-query takes too long to run

I have a SQL update query that runs with my test data, but doesn't complete (2 hours or more) with my production data.

The purpose of the query

I have an ADDRESSES table that uses code strings instead of IDs. So for example ADDRESSES.COUNTRY_CODE = "USA" instead of 3152. For referential integrity, I am changing these code strings to code IDs.

Schema

ADDRESSES

  • ADDR_ID (PK)
  • COUNTRY_CODE (varchar)
  • Address line 1 (varchar)
  • etc.

COUNTRY_CODES

  • CODE_ID (PK)
  • CODE_STRING (varchar)
  • etc.

Steps

First, I create a temporary table to store the address records with the appropriate code ID:

CREATE TABLE ADDRESS_TEMP
AS
   SELECT ADDR_ID, CODE_ID
     FROM    ADDRESSES
          LEFT JOIN
             COUNTRY_CODES
          ON ADDRESSES.COUNTRY_CODE = CODE_STRING

Second, I null the COUNTRY_CODE column and change its type to NUMBER.

Third I set the COUNTRY_CODE column to the code IDs:

UPDATE ADDRESSES
   SET COUNTRY_CODE =
          (SELECT ADDRESS_TEMP.CODE_ID
             FROM ADDRESS_TEMP
            WHERE ADDRESS_TEMP.ADDR_ID = ADDRESSES.ADDR_ID)

It is this third step that is taking hours to complete (2 hours and counting). The ADDRESSES table has ~356,000 records. There is no error; it is still running.

Question

Why isn't this update query completing? Is it dramatically inefficient? I think I can see how the sub-query might be an N2 algorithm, but I'm inexperienced with SQL.



via Chebli Mohamed

swap image and toggle div onclick

I have a dynamically populated unordered list. Every other list item is hidden. First list item contains an image, when clicked displays the list item immediately following. That part of my code is working fine. What I can't seem to figure out is how to swap the toggle image onclick. Right now the image stays the same

thank you for any help you can provide

$(document).ready(function () {
  $(".slidingDiv").hide();

  $('.show_hide').click(function (e) {
    $(".slidingDiv").slideToggle("slow");
    var val = $(this).src() == "http://ift.tt/1FdgyXH" ? "http://ift.tt/1MYsyCI" : "http://ift.tt/1FdgyXH";
    $(this).hide().src(val).fadeIn("slow");
    e.preventDefault();
  });
});
<script src="http://ift.tt/1qRgvOJ"></script>
<ul id="storeTable">
  <li id="one" class="alwaysVisable">
    <h3>Title</h3>
    <p class="descript">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    <img src="http://ift.tt/1MYsyCI" class="show_hide" width="32" height="32">
  </li>
  <li class="slidingDiv">
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum.
  </li>
  <li id="two" class="alwaysVisable">
    <h3>Title</h3>
    <p class="descript">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
    <img src="http://ift.tt/1MYsyCI" class="show_hide" width="32" height="32">
  </li>
  <li class="slidingDiv">
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum.
  </li>
</ul>


via Chebli Mohamed

How to go back to an already launched activity in android

I want to go back to an already launched activity without recreating again.

  @Override
    public void onBackPressed() {
     Intent i = new Intent(SecondActivity.this, FirstActivity.class);
     this.startActivity(i);

    }

Instead of doing is there any other way to go back to another activity which is already created, which I get back with " Back button "



via Chebli Mohamed

how to shorten source code using whenall in order to optimize speed

I have used following code and its supposed to be used for calling more than 100,000 urls .

As its taking long time to finish the process , I am trying to find a better way to optimize the code.

I have read other questions like mine and few people suggested to remove toarray but there were example of how to do it.

Any comments would be appreciated.

private async Task ProcessAllURLSAsync(List<string> urlList)
{
    IEnumerable<Task> CallingTasksQuery =
        from url in urlList select ProcessURLAsync(url);

    Task[] CallingTasks = CallingTasksQuery.ToArray();

    await Task.WhenAll(CallingTasks);
}

private async Task ProcessURLAsync(string url)
{
    await CallURLAsync(url);
}

private async Task CallURLAsync(string url)
{
    var content = new MemoryStream();
    var webReq = (HttpWebRequest)WebRequest.Create(url);
    using (WebResponse response = await webReq.GetResponseAsync())
    {
    }
}



via Chebli Mohamed

How to map a Perforce depot's folder to an arbitrary local folder?

I have the following structure on the Perforce server:

MyDepot
  + MyProject
    + MySubProject
      + trunk
        + ... trunk folders/files ...

I have my Eclipse workspace for MySubProject in:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject

If I get the latest revision with a Perforce workspace of:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject

I get:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject\
  + MyDepot
    + MyProject
      + MySubProject
        + trunk
          + ... trunk folders/files ...

I'd prefer:

C:\Users\<my username>\Documents\eclipse.wkspcs\MySubProject\
  + ... trunk folders/files ...

Can I achieve this and if, how?

I found the P4V manual page Defining a Workspace View but it doesn't seem to cover what I want. (There's a garbled sentence under point 2. but this isn't essential in this respect, is it?)



via Chebli Mohamed

Tokenizing a string in Prolog using DCG

Let's say I want to tokenize a string of words (symbols) and numbers separated by whitespaces. For example, the expected result of tokenizing "aa 11" would be [tkSym("aa"), tkNum(11)].

My first attempt was the code below:

whitespace --> [Ws], { code_type(Ws, space) }, whitespace.
whitespace --> [].

letter(Let)     --> [Let], { code_type(Let, alpha) }.
symbol([Sym|T]) --> letter(Sym), symbol(T).
symbol([Sym])   --> letter(Sym).

digit(Dg)        --> [Dg], { code_type(Dg, digit) }.
digits([Dg|Dgs]) --> digit(Dg), digits(Dgs).
digits([Dg])     --> digit(Dg).

token(tkSym(Token)) --> symbol(Token). 
token(tkNum(Token)) --> digits(Digits), { number_chars(Token, Digits) }.

tokenize([Token|Tokens]) --> whitespace, token(Token), tokenize(Tokens).
tokenize([]) --> whitespace, [].  

Calling tokenize on "aa bb" leaves me with several possible responses:

 ?- tokenize(X, "aa bb", []).
 X = [tkSym([97|97]), tkSym([98|98])] ;
 X = [tkSym([97|97]), tkSym(98), tkSym(98)] ;
 X = [tkSym(97), tkSym(97), tkSym([98|98])] ;
 X = [tkSym(97), tkSym(97), tkSym(98), tkSym(98)] ;
 false.

In this case, however, it seems appropriate to expect only one correct answer. Here's another, more deterministic approach:

whitespace --> [Space], { char_type(Space, space) }, whitespace.
whitespace --> [].

symbol([Sym|T]) --> letter(Sym), !, symbol(T).
symbol([])      --> [].
letter(Let)     --> [Let], { code_type(Let, alpha) }.

% similarly for numbers

token(tkSym(Token)) --> symbol(Token).

tokenize([Token|Tokens]) --> whitespace, token(Token), !, tokenize(Tokens).
tokenize([]) --> whiteSpace, [].

But there is a problem: although the single answer to token called on "aa" is now a nice list, the tokenize predicate ends up in an infinite recursion:

 ?- token(X, "aa", []).
 X = tkSym([97, 97]).

 ?- tokenize(X, "aa", []).
 ERROR: Out of global stack

What am I missing? How is the problem usually solved in Prolog?



via Chebli Mohamed

Git issues with shared folders in Vagrant

I have never seen this issue before while using Vagrant, so I'm hoping this makes sense to someone. I have a folder that contains a git repository, that is being synced with a Vagrant machine running CentOS 6.5, and seeing some inconsistencies with Git.

On my host machine (Mac OSX) if I run git status I get the following:

 ~/Folder/repo$ git status
 On branch master
 Your branch is up-to-date with 'origin/master'.
 nothing to commit, working directory clean

But if I run the same command within my vagrant box, I get the following:

vagrant@localhost ~/repo$ git status                                                                                                                 master
# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   .codeclimate.yml
#   modified:   .gitattributes
#   modified:   .gitignore
#   modified:   CONTRIBUTING.md
#   modified:   app/commands/.gitkeep
#   modified:   app/commands/CreateModule.php
#   modified:   app/commands/FbAdRevenue.php
....

And the list goes on, basically git locally seems to think that every single file has been modified and not committed which is not true. Any idea why this would be the case and how to fix it?



via Chebli Mohamed

Sparql insert data not working

I'm a newbie to Sparql, but I am unable even to make a simple insert data query, or so it seems.

I'm using Apache Fuseki as working server; I'm in a graph, and I'm trying to make this query work:

PREFIX oa: <http://ift.tt/1FdgyHl;
PREFIX rdfs: <http://ift.tt/1cmhdKn;

INSERT DATA{             
  [ a 
    oa:Annotation ;                    
    rdfs:label "Title";                    
  ] .                    
}

But it doesn't matter what I do, I keep getting this error:

Error 400: SPARQL Query: No 'query=' parameter

This is even a semplified code, I tried many queries even more complex, but the result doesn't change...



via Chebli Mohamed

Ionic Changes Content-Type

Ok I have to make a simple GET request that work in Postman but not in the Ionic code. I have determined that the reason is that the API treats incoming requests differently based on Content-Type. application/json works text doesn't.

    headers: {
      "Content-Type": 'application/json; charset=UTF-8',
      "Accept": 'application/json; charset=UTF-8'
    },

As you can see I'm setting the header to try to force application/json but when I sniff the request it has changed to text/html somehow. How do I force Ionic to take my Content-Type as definitive?



via Chebli Mohamed

user authentication methods for apple watch app

I have an iPad and iPhone application,which runs on user session and requires login and session to be maintained throughout application life cycle. Now I want to create Apple watch app for same app. What are the best ways to do login and maintain session on Apple watch. User session expires if app is idle for more than 20 minutes.



via Chebli Mohamed

Using FileReader.readAsArrayBuffer() on changed files in Firefox

I'm running into an odd problem using FileReader.readAsArrayBuffer that only seems to affect Firefox (I tested in the current version - v40). I can't tell if I'm just doing something wrong or if this is a Firefox bug.

I have some JavaScript that uses readAsArrayBuffer to read a file specified in an <input> field. Under normal circumstances, everything works correctly. However, if the user modifies the file after selecting it in the <input> field, readAsArrayBuffer can get very confused.

The ArrayBuffer I get back from readAsArrayBuffer always has the length that the file was originally. If the user changes the file to make it larger, I don't get any of the bytes after the original size. If the user changes the file to make it smaller, the buffer is still the same size and the 'excess' in the buffer is filled with character codes 90 (capital letter 'Z' if viewed as a string).

Since this code is so simple and works perfectly in every other browser I tested, I'm thinking it's a Firefox issue. I've reported it as a bug to Firefox but I want to make sure this isn't just something obvious I'm doing wrong.

The behavior can be reproduced by the following code snippet. All you have to do is:

  1. Browse for a text file that has 10 characters in it (10 is not a magic number - I'm just using it as an example)
  2. Observe that the result is an array of 10 items representing the character codes of each item
  3. While this is still running, delete 5 characters from the file and save
  4. Observe that the result is still an array of 10 items - the first 5 are correct but the last 5 are all 90 (capital letter Z)
  5. Now added 10 characters (so the file is now 15 characters long)
  6. Observe that the result is still an array of 10 items - the last 5 are not returned
function ReadFile() {
  var input = document.getElementsByTagName("input")[0];
  var output = document.getElementsByTagName("textarea")[0];

  if (input.files.length === 0) {
    output.value = 'No file selected';
    window.setTimeout(ReadFile, 1000);
    return;
  }

  var fr = new FileReader();
  fr.onload = function() {
    var data = fr.result;
    var array = new Int8Array(data);
    output.value = JSON.stringify(array, null, '  ');
    window.setTimeout(ReadFile, 1000);
  };
  fr.readAsArrayBuffer(input.files[0]);

  //These two methods work correctly
  //fr.readAsText(input.files[0]);
  //fr.readAsBinaryString(input.files[0]);
}

ReadFile();
<input type="file" />
<br/>
<textarea cols="80" rows="10"></textarea>

In case the snippet does not work, the sample code is also available as a JSFiddle here: http://ift.tt/1MYsymg



via Chebli Mohamed

intellij internal webserver using htaccess

IntelliJ 14 has a built-in Webserver where you can run html-files on localhost port 63342. Is there any possibility to use rewrite rules (like modrewrite) within a .htaccess file or something similar?

Or do I have to install a local webserver for this?

Regards, Jens



via Chebli Mohamed

When using a RegEx in AutoFixture ISpecimenBuilder, Why do I always get back the same value?

My builder is set up to either deal with a Parameter or a Property. This may change in the future, but for now this is what I have in my builder:

public class UserNameBuilder : ISpecimenBuilder
{
    public object Create(object request, ISpecimenContext context)
    {
       var propertyInfo = request as PropertyInfo;
        if (propertyInfo != null && propertyInfo.Name == "UserName" && propertyInfo.PropertyType == typeof(string))
        {
            return GetUserName();
        }

        var parameterInfo = request as ParameterInfo;
        if (parameterInfo != null && parameterInfo.Name == "userName" && parameterInfo.ParameterType == typeof(string))
        {
            return GetUserName();
        }

        return new NoSpecimen(request);
    }

    static object GetUserName()
    {
        var fixture = new Fixture();
        return new SpecimenContext(fixture).Resolve(new RegularExpressionRequest(@"^[a-zA-Z0-9_.]{6,30}$"));
    }
}

My UserName object is a ValueType object and is as follows:

public class UserName : SemanticType<string>
{
    private static readonly Regex ValidPattern = new Regex(@"^[a-zA-Z0-9_.]{6,30}$");

    public UserName(string userName) : base(IsValid, userName)
    {
        Guard.NotNull(() => userName, userName);
        Guard.IsValid(() => userName, userName, IsValid, "Invalid username");
    }

    public static bool IsValid(string candidate)
    {
        return ValidPattern.IsMatch(candidate);
    }

    public static bool TryParse(string candidate, out UserName userName)
    {
        userName = null;

        try
        {
            userName = new UserName(candidate);
            return true;
        }
        catch (ArgumentException ex)
        {
            return false;
        }
    }
}

The UserName class inherits from SemanticType which is a project that provides a base for my value types.

Whenever I use AutoFixture as follows:

var fixture = new Fixture();
fixture.Customizations.Add(new UserNameBuilder());

var userName = fixture.Create<UserName>();

I always get the value "......" I thought I would get a different value each time. Is what I'm seeing expected behavior?

Thanks



via Chebli Mohamed

swift remoteControlReceivedWithEvent giving fatal error: unexpectedly found nil while unwrapping an Optional value

I am using below function to play/pause the music and I am implementing remote controls:

in ViewController.swift :

static let sharedInstance = ViewController()
@IBOutlet var PausePlay: UIButton!


var BackgroundAudio = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ants", ofType: "mp3")!), error: nil)

//in info.playlist I have added 'Required background modes and add to idem 0 ap plays audio airplay then below code to play even when iphone is locked: -marcin

    PausePlay.setTitle("Play", forState: UIControlState.Normal)

    AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)

    // Do any additional setup after loading the view, typically from a nib.
    PausePlay.setTitle("Play", forState: UIControlState.Normal)
    if NSClassFromString("MPNowPlayingInfoCenter") != nil {
        let image:UIImage = UIImage(named: "logo_player_background")!
        let albumArt = MPMediaItemArtwork(image: image)
        var songInfo: NSMutableDictionary = [
            MPMediaItemPropertyTitle: "Ants",
            MPMediaItemPropertyArtist: "The App",
            MPMediaItemPropertyArtwork: albumArt
        ]
        MPNowPlayingInfoCenter.defaultCenter().nowPlayingInfo = songInfo as [NSObject : AnyObject]
    }
    if (AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)) {
        println("Receiving remote control events")
        UIApplication.sharedApplication().beginReceivingRemoteControlEvents()
    } else {
        println("Audio Session error.")
    }

in AppDelegate.swift I have this for remote control:

override func remoteControlReceivedWithEvent(event: UIEvent) {
        if event.type == UIEventType.RemoteControl {
        if event.subtype == UIEventSubtype.RemoteControlPlay {
            println("received remote play")
            ViewController.sharedInstance.FuncPausePlay() // these are producing terrible error
        } else if event.subtype == UIEventSubtype.RemoteControlPause {
            println("received remote pause")
            ViewController.sharedInstance.FuncPausePlay() // these are producing terrible error
        } else if event.subtype == UIEventSubtype.RemoteControlTogglePlayPause {
            println("received toggle")
            ViewController.sharedInstance.BackgroundAudio.stop()
        }
    }
}

when I am hitting play button then app works file on my phone (it plays the sound) but I am getting below info in Xcode error window:

Receiving remote control events 2015-08-31 19:33:42.735 The App[1501:292732] Unable to simultaneously satisfy constraints. Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) ( "", "", "", "", "", "" ) Will attempt to recover by breaking constraint Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in may also be helpful.

then when I lock my phone, sound is still playing (which if great) but when I am hitting pause button on remote control screen (when my phone is locked) then app is freezing / stopping and I get below info in Xcode :

received remote pause fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

What am I doing wrong? Please help.



via Chebli Mohamed

How can I visualize a data.frame with a values column and a label column in R?

I'm using the pdf command and ggplot2 to create couple different types of graphs and while I'm at it I'd like to throw in some simple tables (with, for example, column labels being coefficient names and rows having values) but I'm not sure to make a "plot" out of that without going separately into excel to make a table (but then I don't know how to insert it into the pdf I generate with R)

For example suppose I've got a data.frame like this one:

set.seed(1)
foo = data.frame(val1=rnorm(5), val2=rnorm(5), columnLabels=c('A','B','C','D','F'))

Is there a simple way to "plot" a simple table with those column labels, with row labels like c('Val 1', 'Val2') and with the corresponding values?



via Chebli Mohamed

Email Attachment From Lotusscript Agent

I have documents that get processed via a scheduled LotusScript agent. Each document has a $FILE field which is a jpg photo. In my agent, I want to take that photo on the document and email it to a specified address. Is this possible with a scheduled LotusScript agent?



via Chebli Mohamed

NetLogo: how to make the calculation of turtle movement easier?

I am working with NetLogo code written with somebody else (freely available to public). I try to understand how the procedure of turtle moving is elaborated and, most important - how make it computationally faster without loosing sensitivity of turtle movement in relation to worlds' patches?

I suppose that the most of the calculation time is used to calculate the distance of each step of turtle movement - I would like to measure only one variable from patch of turtle's origins to last patch where it will stay. I have decoded some of features but I am still not able to reproduce them. I'll really appreciate any help !

My understanding what the procedure could accomplish:

enter image description here

to move-turtles                                                                    
   ifelse perceptdist = 0                                                           
    [ifelse patch-ahead 1 != nobody 
     [rt random moveangle lt random moveangle                                      
      let xcorhere [pxcor] of patch-here                                           
      let ycorhere [pycor] of patch-here                                           
      fd 1
      let xcornext [pxcor] of patch-here                                           
      let ycornext [pycor] of patch-here                                           
      set dist sqrt (xcor * xcor + ycor * ycor)                                        
      set t_dispers (t_dispers + 1)                                                 
      set energy (energy - (1 / efficiency))                                       
      let flightdistnow sqrt ((xcornext  - xcorhere) * (xcornext  - xcorhere) + (ycornext - ycorhere) * (ycornext - ycorhere))   
      set flightdist (flightdist + flightdistnow)

    ][]]     

   [let np patches in-radius perceptdist          ; find the patch with the highest totalattract value within perception range                                 
    let bnp max-one-of np [totalattract]                                              
    let ah [totalattract] of patch-here
    let xcorhere [pxcor] of patch-here
    let ycorhere [pycor] of patch-here                                             
    let abnp [totalattract] of bnp                                                 
    ifelse abnp - ah > 2 and random-float 1 < 0.1                                  
     [move-to bnp                                     ; move to the patch with the highest attractivity value
      let xbnp [pxcor] of bnp                                 
      let ybnp [pycor] of bnp
      let flightdistnow sqrt ((xbnp - xcorhere) * (xbnp - xcorhere) + (ybnp - ycorhere) * (ybnp - ycorhere)) 
      set t_dispers (t_dispers + flightdistnow)                
      set energy (energy - (flightdistnow / efficiency))      ; how the turtle decision to stay/move further is made - ratio of turtle energy/efficiency  
      set flightdist (flightdist + flightdistnow)
      set dist sqrt (xcor * xcor + ycor * ycor)               

   [rt random moveangle lt random moveangle                                        
    set dist sqrt (xcor * xcor + ycor * ycor)                                      
    set t_dispers (t_dispers + 1)                                                  
    set energy (energy - (1 / efficiency))                                         
    let xcorhere2 [pxcor] of patch-here                                           
    let ycorhere2 [pycor] of patch-here                                            
    fd 1
    let xcornext2 [pxcor] of patch-here                                            
    let ycornext2[pycor] of patch-here                                             
    set dist sqrt (xcor * xcor + ycor * ycor)                                         
    let flightdistnow sqrt ((xcornext2  - xcorhere2) * (xcornext2  - xcorhere2) + (ycornext2 - ycorhere2) * (ycornext2 - ycorhere2))   
    set flightdist (flightdist + flightdistnow)

end  



via Chebli Mohamed

How to prevent loading the same data over and over in angularJS

I have an object that contains some data that I need to load when my application starts. Once its loaded I need to be able to reuse in multiple places on my application.

What is the best way to do this?

Right now I have a factory that I inject into my controller and I pull the data, the problem is that I'm doing the data pull multiple times.

What would be the best way to pull the data only when I load the application? I would only need to access the data on my templates and pull the correct Key Value from the object where I need.



via Chebli Mohamed

Indexed View in SQL Server

Can I create an index on a view which references synonyms which point to a linked server? Since the view isn't based on local tables I wasn't sure if it was possible.



via Chebli Mohamed

Is Telegram bot token secure: does SSL encrypt the requested URL?

Is Telegram bot token secure as long as it's being use in url for each api method call? Is there a risk that someone steal Telegram token in the way to Telegram servers ?

Or in other words: Does SSL encrypt the url itself ?



via Chebli Mohamed

please help !! . I can't Create any SharedPrefrences

I usually use this code for create sharedPrefs file :

SharedPrefrences SP = getSharedPrefrences("MYPREF",0);
SP.getString("Username","x");

But now if i see this directory :

"/data/data/packageName/" 

There is not any shared_prefs directory. Another thing : if I use Editor its work properly. Please help me ..



via Chebli Mohamed

a href not working with a bare web page

I've been looking around for a solution to the problem I'm having, but it seems that none of the solutions on SO address my issue.

I was having the dreaded issue where the a href tag in my HTML does not actually take me to the link. At first, I tried removing the JavaScript includes, wondering if something in the JavaScript portion was messing up the page.

Then I removed the CSS portion as well, and ultimately removed everything until the page consisted of simply the header information for the HTML page and only the a href tag. I also changed the link to a non-existent page (to force a 404 error).

When clicking on the link, it keeps me on the current page and doesn't take me to the referenced page (or even give me a 404 error). Following is the stripped out code (everything but the commented out portion):

 <html>
 <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, user-scalable=no" />
    <title>test</title>

    <meta name="description" content="test1" />

    <meta name="keywords" content="test2" />
 </head>

  <a href="test.html">Support</a/>

 </html>

Thanks for the help.



via Chebli Mohamed

Sorting a list according to date [duplicate]

This question already has an answer here:

I have a struct and a list as follow, I just wanted to sort the Inputpoints according to date. I have used the following commands but I can not see any sorting.

public struct Points
{
    public Date Date;
    public double Quantity;
}
_test = new List<Points>(InputPoints);
_test.OrderBy(t => t.Date);

Thanks



via Chebli Mohamed

deserialize json to c# string

I apologize if I'm asking the same question again, but I have a simple JSON string that I need to deserialize. But I can use .NET 3.5 only. Here's my string:

{
  "DataCon": {
    "ActivityID": "ACT001",
    "RequestID": 123,
    "CRMID": 998989,
    "LeadID": "LEAD001",
    "ProcessName": "PROC",
    "ContatcID": "CON001"
  },
  "Errors": [

  ],
  "Warnings": [

  ]
}

Please help me find a solution using .NET 3.5 only



via Chebli Mohamed

Guess I'm Not Understanding how httpcontext.current.response.binarywrite works

Let me start by saying if I'm making this overly complicated, please, please offer suggestions on how to simplify!! I'm trying to create some logic that will let users export the contents on the screen to a PDF file. The contents contains multiple highcharts graphs, so I need for the html to be rendered completely to the page so I can grab the svg information to pass into the PDF file. Since the page has been rendered completely, the only way I know to pass the rendered html back to the server is through Web Services. Web Services is calling a .cs file where the PDF functionality is located. I can set a break point in the .cs file at the end of the pdf function, and it is hitting it. The problem is, it's returning an error of "200 OK parsererror SyntaxError: Unexpected token %".

Now, I create a dummy html string in my C# codebehind and call the .cs file from the codebehind, and it creates a PDF file with no issues at all. So my question is, why would the class work when being called from a codebehind, but not from Web Services? The only thing I can think of, is that it has something to do with a postback? My code is below:

JavaScript that is calling the Web Service..I can step all the way through the web service and class functions being called, they are making it to the end, but it's returning to the error function with 200 OK parsererror SyntaxError: Unexpected token %

function checkSplash() {
    timesChecked++;
    if (loadImages >= document.getElementsByName('img').length || timesChecked * checkInterval >= maxLoadTime) {
        clearInterval(intervalID);

        if (document.getElementById("exportDiv") != null) {
            var mydata = {
                src: document.getElementById("export_pdf").innerHTML
            }

            $.ajax({
                type: "post",
                contentType: "application/json; charset=UTF-8",
                url: "../WebServices/print.asmx/export",
                data: JSON.stringify(mydata),
                dataType: "json",
                success: function (response) {
                    alert("here");
                    location.reload(true);
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert(xhr.status + ' ' + xhr.statusText + ' ' + textStatus + ' ' + errorThrown);
                }
            })
        }
    }
}

Web Service being called...this function is identical the a test function I created in the codebehind. The codebehind test function works and creates the PDF document with no issues. But when this gets called from the javascript, it returns the error

using DMC.Classes;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DMC.WebServices
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]

    public class print : System.Web.Services.WebService
    {
        [WebMethod]
        public bool export(string src)
        {
            string fileName = null;
            export dmc = new export();

            fileName = " Behavior Statistics YTD ";

            dmc.exportPDF(fileName, "Portrait", src);

            return true;
        }
    }
}

Finally, the .cs methods being used:

using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using NReco.PdfGenerator;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace DMC.Classes
{
    public class export 
    {
        public void exportPDF(string fileName, string Orientation, string html)
        {
            HtmlToPdfConverter pdf = new HtmlToPdfConverter();

            html = html.Replace("\n", "");
            html = html.Replace("\t", "");
            html = html.Replace("\r", "");
            html = html.Replace("\"", "'");

            switch (Orientation)
            {
                case "Portrait":
                    pdf.Orientation = PageOrientation.Portrait;
                    break;
                case "Landscape":
                    pdf.Orientation = PageOrientation.Landscape;
                    break;
                default:
                    pdf.Orientation = PageOrientation.Default;
                    break;
            }

            pdf.Margins.Top = 25;
            pdf.PageFooterHtml = createPDFFooter();

            var pdfBytes = pdf.GeneratePdf(createPDFScript() + html + "</body></html>");

            HttpContext.Current.Response.ContentType = "application/pdf";
            HttpContext.Current.Response.ContentEncoding =  System.Text.Encoding.UTF8;
            HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".pdf");
            HttpContext.Current.Response.BinaryWrite(pdfBytes);
            HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

        private string createPDFScript()
        {
            return "<html><head><style>td,th{line-height:20px;} tr { page-break-inside: avoid }</style><script>function subst() {var vars={};var x=document.location.search.substring(1).split('&');for(var i in x) {var z=x[i].split('=',2);vars[z[0]] = unescape(z[1]);}" +
        "var x=['frompage','topage','page','webpage','section','subsection','subsubsection'];for(var i in x) {var y = document.getElementsByClassName(x[i]);" +
        "for(var j=0; j<y.length; ++j) y[j].textContent = vars[x[i]];}}</script></head><body onload=\"subst()\">";
        }

        private string createPDFFooter()
        {
            return "<div><table style='font-family:Tahoma; font-size:9px; width:100%'><tr><td style='text-align:left'>Research Dept|RR:mm:jpg</td><td style='text-align:right'>Page <span class=\"page\"></span> of <span class=\"topage\"></span></td></div>";
        }
    }
}



via Chebli Mohamed

C# HLSL/XNA/MonoGame Problems

First of all, im new to shaders and xna.

I've been trying to follow this tutorial: http://ift.tt/1UbWeP2

I've done everything he said, I even ended up copy/pasting some parts to be totally sure although – it still won't work.

    sampler s0;
    texture lightMask;
    sampler lightSampler=sampler_state {
      Texture=<lightMask>;
    }
    ;
    float4 PixelShaderLight(float2 coords:TEXCOORD0):COLOR0 {
      float4 color=tex2D(s0, coords);
      float4 lightColor=tex2D(lightSampler, coords);
      return color * lightColor;
    }
    technique Technique1 {
      pass P0 {
        PixelShader=compile ps_4_0_level_9_1 PixelShaderLight();
      }
    }

The problem is that when I apply the pass 0 everything goes black.

My guess is that the lightcolor is returning zero. The lightmask is a renderTarget where I've painted my lights on.

I really dont know why lightcolor would return zero. If that is the case, could anyone give me a hint in what I'm doing wrong?

Here is my main class if you want to look at it:

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace TestingGame
{
    public class TestingGame : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Location loc;

        public static Texture2D lightMask;
        public static Texture2D img;
        public static Effect effect1;
        RenderTarget2D lightsTarget;
        RenderTarget2D mainTarget;

        public TestingGame()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            loc = new Location(20,20);

            var pp = GraphicsDevice.PresentationParameters;
            lightsTarget = new RenderTarget2D(
            GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);
            mainTarget = new RenderTarget2D(
            GraphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight);

            base.Initialize();
        }

        protected override void LoadContent()
        {

            spriteBatch = new SpriteBatch(GraphicsDevice);

            lightMask = Content.Load<Texture2D>("lightmask.png");
            img = Content.Load<Texture2D>("img.png");
            effect1 = Content.Load<Effect>("lighteffect");

        }

        protected override void UnloadContent()
        {
        }

        protected override void Update(GameTime gameTime)
        {
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();
            if(loc.Equals(new Location(21,20)))
                System.Console.WriteLine("Working");
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.SetRenderTarget(lightsTarget);
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Additive);

            spriteBatch.Draw(lightMask, new Vector2(20, 20), Color.Red);

            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(mainTarget);
            GraphicsDevice.Clear(Color.Transparent);
            spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend);

            spriteBatch.Draw(img, new Vector2(50,50));

            spriteBatch.End();

            GraphicsDevice.SetRenderTarget(null);
            GraphicsDevice.Clear(Color.Black);

            spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

            effect1.Parameters["lightMask"].SetValue(lightsTarget);
            effect1.CurrentTechnique.Passes[0].Apply();
            spriteBatch.Draw(mainTarget, Vector2.Zero, Color.White);

            spriteBatch.End();

            base.Draw(gameTime);
        }
    }
}



via Chebli Mohamed

`using` declaration for a user-defined literal operator

Is it possible to have a using declaration for the literals operator, operator ""?

E.g.,

#include <chrono>

namespace MyNamespace
{
  constexpr std::chrono::hours operator "" _hr(unsigned long long n){
    return std::chrono::hours{n};
  }

  // ... other stuff in the namespace ...
}

using MyNamespace::operator"";    // DOES NOT COMPILE!

int main()
{
  auto foo = 37_hr;
}

My work-around has been to put these operators in their own nested namespace called literals, which allows using namespace MyNamespace::literals;, but this seems somewhat inelegant, and I don't see why the using directive can't be used for operator functions in the same way as it can for any other functions or types within a namespace.



via Chebli Mohamed

Size of PriorityQueue increases when a non-comparable object is added

Consider the following code:

import java.util.PriorityQueue;

public class Test {

    public static void main(String argv[]) {
        PriorityQueue<A> queue = new PriorityQueue<>();
        System.out.println("Size of queue is " + queue.size()); // prints 0
        try {
            queue.add(new A());
        } catch (ClassCastException ignored) { }
        System.out.println("Size of queue is " + queue.size()); // prints 1
    }

} 
class A { } // non-comparable object

In this code, an object, which is explicitly non-comparable, is added to a PriorityQueue. As expected per PriorityQueue.add Javadoc, this code throws a ClassCastException because the object is not comparable.

However, it seems that the size of the queue is still increased, although an exception was thrown.

I would have expected both print statements to output 0 but the second one actually outputs 1, as if an object had been added to the queue.

I find this really strange, is this behaviour expected? If so, what is the reason behind this and where is it documented? I can't find anything related to this.



via Chebli Mohamed

CSS @Keyframes - experts opinion wanted

this is my 'very first' foray into keyframe animation. I was put off before by the alleged inability to dynamically change hard coded CSS values on the fly via JavaScript.

I Googled around a bit to find it 'can' be done but with a lot of fiddly work finding, removing and replacing parts of or whole stylesheets.

Anyway, here's my effort. The eventual goal of this particular script is to be the bounce of clock hand. I can already do this with transition and cubic bezier but can only get one bounce in. I've seen this effect using various js libraries etc but you know how it is - you like to roll your own.

My question is - Is there anything glaringly wrong with my method below. Ignore the trivia, it's just a test. What I want looking at is my GenerateKeyFrames() function and the two methods of calling it.

Thanks for any info.

    var d = document;
    var incr = 1;
    var step = -6; //Initial start pos.

    var coreCss = 'display: block;position: absolute;'
               +'left: 100px;top: 10px;height: 95px;'
               +'width: 4px;background-color: #000;'
               +'transform-origin: center bottom;';

    var initialAniCss = 'animation: reGen'+incr+' 1s 1 forwards;';
    coreCss += initialAniCss;

    var elementToAnimate = d.createElement('div');
    elementToAnimate.setAttribute('style', coreCss);
    d.body.appendChild(elementToAnimate);

    function GenerateKeyFrames() {

    /* Remove previous 'tmpSheet' stylesheet */
    var currSheet = (d.getElementById('tmpSheet'));
    if (currSheet) {
        //currSheet.parentNode.removeChild(currSheet);// Doesn't seem as smooth as other 2 below!
        //currSheet.remove(); - Not IE, shame.
        currSheet.outerHTML = '';
    }

    /* Movement in degrees */
    var p1 = step;
    var p2 = step+6;
    var p3 = step+4;
    var p4 = step+6;
    var p5 = step+5; 
    var p6 = step+6;

    /* Create new keyframe. Must have new name! Adding an incrementing var to name does ok */
    var frames = '@keyframes reGen'+incr+' { '
    +'0% { transform: rotate('+p1+'deg) translateZ(0); animation-timing-function: ease-in;}'
    +'25% { transform: rotate('+p2+'deg) translateZ(0); animation-timing-function: ease-out;}'
    +'45% { transform: rotate('+p3+'deg) translateZ(0); animation-timing-function: ease-in;}'
    +'65% { transform: rotate('+p4+'deg) translateZ(0); animation-timing-function: ease-out;}' 
    +'75% { transform: rotate('+p5+'deg) translateZ(0); animation-timing-function: ease-in;}'
    +'85%,100% { transform: rotate('+p6+'deg) translateZ(0);animation-timing-function: ease-out;}}';

    /* Create new tmpSheet style sheet to head */
    var s = document.createElement( 'style' );
    s.setAttribute("id", "tmpSheet");
    s.innerHTML = frames;
    document.getElementsByTagName('head')[0].appendChild(s);

    /* Put it all together and it's ready to go */ 
    var newAni = 'animation: reGen'+incr+' 1s 1 forwards;';
    coreCss += newAni;
    elementToAnimate.setAttribute('style', coreCss);
    d.body.appendChild(elementToAnimate);
}
GenerateKeyFrames();

/* Can be called on animation end - or timed function rep().
elementToAnimate.addEventListener("animationend",function(e) {
    incr++;
    step += 6;
    elementToAnimate.removeAttribute("style");
    GenerateKeyFrames();
    },false);
*/

function rep() {
    incr++;
    step += 6;
    elementToAnimate.removeAttribute("style");
    GenerateKeyFrames();
setTimeout(rep, 2000);
}
rep();


via Chebli Mohamed

How to consume npm react-art module without bundling?

There is no CDN for React-art library. So, I installed it via npm install react-art in the local asp.net project.

In the cshtml file where I use the ReactART object, I used the following script:

  <script src="http://ift.tt/1KXYNNU"></script>
  <script src="http://ift.tt/1ERkbBe"></script>
  <script src="http://ift.tt/1jyb1yI"></script>
  <script src="http://ift.tt/1JmkwQq"></Script>
  <script src="http://ift.tt/1KXYPp8"></script>
  <script src="..\..\node_modules\react-art\lib\reactart.js"></script>

But I can't get the reference to the ReactART object.

How can I consume react-art and it's dependencies?



via Chebli Mohamed

Force wordcloud python module to include all words

I'm using the wordcloud module in Python by Andreas Mueller to visualize results of a survey my students will complete. Brilliant module, very nice pictures, however I have trouble making it recognize all words, even when setting stopwords=None and ranks_only=True. The survey responses are between one and three words long and may contain hyphens.

Here is an example. First I install dependencies in my Jupyter notebook:

import matplotlib.pyplot as plt
%matplotlib inline
from wordcloud import WordCloud
from scipy.misc import imread

Then suppose I put all the responses into a string:

words = "do do do do do do do do do do re re re re re mi mi fa fa fa fa fa fa fa fa fa fa-so fa-so fa-so fa-so fa-so so la ti do"

Then I execute the plot:

wordcloud = WordCloud(ranks_only = True,stopwords=None).generate(words)
plt.imshow(wordcloud)
plt.axis('off')
plt.show()

But for some reason it ignores "do" and "fa-so" despite their high frequency.

Any tips? Besides "don't use a word cloud". It is a silly survey and it invites a silly visualization. Thanks.

Update

Still unable to include hyphened words (e.g. "fa-so"), they just drop out.



via Chebli Mohamed

Differences between using a method reference and function object in stream operations?

When using Java 8 streams I often find that I need to refactor a multi-statement lambda expression. I will illustrate this with a simple example. Assume I have started writing this code:

Stream.of(1, 3).map(i -> {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
}).forEach(System.out::println);

Now I am not very fond of the large lambda expression in the map call. Hence, I want to refactor it out of there. I see two options, either I make an instance of Function in my class:

private static Function<Integer, String> mapper = i -> {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
};

and use it like this:

Stream.of(1, 3).map(mapper).forEach(System.out::println);

Or I simply make a method:

private static String map(Integer i) {
    if (i == 1) {
        return "I";
    } else if (i == 3) {
        return "E";
    }
    return "";
}

and use a method reference:

Stream.of(1, 3).map(Test::map).forEach(System.out::println);

Apart from the obvious matter of taste, are there any advantages or drawbacks to either approach?

For example, I know the stack traces become more readable in the method reference case, which is a small advantage.



via Chebli Mohamed

How upload laravel 5.1 project on server step by step [on hold]

i am upload laravel folder on root server , public file on public_html and routing in index.php set correctly

require __DIR__.'/../bootstrap/autoload.php'; 
$app = require_once __DIR__.'/../bootstrap/app.php';

but not work!error log is empty!! when enter domain nothing show is white page please description how upload laravel 5.1 project on server



via Chebli Mohamed

vendredi 8 mai 2015

Control that web page could be loaded only from an specific PC

I'm looking for just some orientation about how to control that an ASP.NET web site could be only loaded from an specific PC.

It seems obvious that the login web page should get the IP address or PC name from the client and check with a database query if that IP address plus the userid account match its database record.

However, catching the IP address with

Request.ServerVariables("REMOTE_ADDR") 

could get a IP address distorted by a firewall, NAT or router configuration. So that option is discarded.

Other option that I've heard is about creating a dll file with a name like "license.dll", and store inside that dll file some credential or IP address or serial number. That data plus the userid account have to be stored in database . When user loads the web page, it should read first that dll file and get the credential inside it, make a query to database and match userid account and dll credential. If matching is correct, then web page is loaded.

Is it possible to store some credential in a dll file and make the web page able to read that dll?

HttpListener with SSL certificate hanging on GetContext()

I've created a windows service which uses a HttpListener to respond to some third-party requests using .NET Framework 4.0. The listener is bound to a https prefix via the following:

listener.Prefixes.Add("https://+:" + Properties.Settings.Default.ListeningPort.ToString() + "/");

The service also self registers the https certificate in the computer store via:

X509Certificate2 certificate = new X509Certificate2(Properties.Settings.Default.HttpsCertPath, "", X509KeyStorageFlags.MachineKeySet);
X509Store store = new X509Store(StoreLocation.LocalMachine);
store.Open(OpenFlags.ReadWrite);
store.Add(certificate);
store.Close();

Further more, the service also registers the certificate - ip:port binding in Http API using the following:

ProcessStartInfo psi = new ProcessStartInfo();            
psi.FileName = "netsh";
psi.Arguments = "http add sslcert ipport=0.0.0.0:" + Properties.Settings.Default.ListeningPort.ToString() + " certhash=" + certificate.Thumbprint + " appid=" + appId;
Process proc = Process.Start(psi);                
proc.WaitForExit();
psi.Arguments = "http add sslcert ipport=[::]:" + Properties.Settings.Default.ListeningPort.ToString() + " certhash=" + certificate.Thumbprint + " appid=" + appId;
Process proc = Process.Start(psi);
proc.WaitForExit();

Everything works well, as expected... EXCEPT... (and here comes the EVIL part): After running for some time, an hour or so, listener.GetContext() no longer returns and the clients get dropped with a "connection reset" like error.

How to extract latest reply text from email, and cut out previous messages?

I am using OpenPop.dll to read emails in my application. I want to read only the reply of the email not original email which it was replied to. But email is read with previous emails in quotes. I want to remove those previous mail contents.

I tried using RegEx for this but that is not very robust way to read replies because different email clients have different reply format.

Is there any way by which I can read only the reply text from mail thread in OpenPop.dll or some other open source library.

Below is how the reply email text looks like when read from OpenPop.dll.

My phone number is 123456789.

On Fri, May 8, 2015 at 2:57 PM,  wrote:

>  Hi,
>
> This mail is regarding your *Phone*. Please reply to this email with your
> *Phone*.
>
> Thanks
>

This format is such that because it was replied from Gmail. Outlook has different format and so does yahoo.

I want to read only

My phone number is 123456789.

Is there any way I could achieve this? Any solution is welcome.

"WriteLine" does not work

I have a problem

I use this code to save to txt file, how to do not to overwrite the file, but would write line by line the next time a function call??

Command WriteLine does not work. Write overwrite the file.

private async Task WriteToFile()
{
    string ResultString = string.Join("\n", locationData.ToArray());

    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(ResultString);

    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var dataFolder = await local.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists);
    var file = await dataFolder.CreateFileAsync("DataFile.txt", CreationCollisionOption.OpenIfExists);

    using (var s = await file.OpenStreamForWriteAsync())
    {
        s.Write(fileBytes, 0, fileBytes.Length);
    }
}

I used Windows Phone 8.1 for my app.

Digitally signing a strong named .NET assembly

I have a .NET assembly which I've strongly named, to put it in the GAC. However, the same assembly is also digitally signed using a .pfx file later on, for digital signature.
I've noticed that this assembly, which has been so dual signed, fails the strong name validation, and does not install in the target machine's GAC.

Could it be possible that the digital signing procedure removes the SN-key generated strong naming procedure?

The digital signature is essential and if the 2 are not compatible, then can the file be signed by the .pfx file instead, as easily as the SN-naming process?

Also, the assembly is in C++/CLI, not in C#.

Merging custom configuration files at runtime in .NET

My question is about working with standard .NET configuration objects and custom configuration elements as well, (which one can define by extending the System.Configuration.ConfigurationSection class). We usually obtain these from the System.Configuration.ConfigurationManager class's methods, GetSection(...) being an example.

The loaded configuration object appears to be a merged configuration object containing the setup present in the application config file (the the app.config or web.config file which a developer may have created) and what is defined in the machine.config file (the latter coming with the .NET Framework installation).

So, we can assume that the configuration is loaded in hierarchical manner with the machine.config first, and any user-defined configuration overlaying that default setup, and could be looked at like this:

  • machine.config
    • app.config (overrides / merges with respective elements found in machine.config )

My goal is to create multiple layers of configuration, so that there might be other config files between (and if possible, after) the machine.config and the app.config file:

  • machine.config
    • custom.config (a custom config interfering between the machine.config and the app.config file)
      • app.config - now app.config is merged with both machine.config and custom.config

Normally, I would write my own configuration manager class and will try to get as far as I could to get the desired result, but assuming the .NET framework has this working for machine.config and app.config, I thought I might benefit from the built-in functionality of the framework. In addition, I do not know how to manually trigger such merging, if I am indeed supposed to resort to a config manager implementation of my own.

So, is it possible to leverage the built-in mechanisms of configuration section/element merging with custom configuration files? I am especially interested in developing and supporting this for custom configuration sections. The System.Configuration namespace contains base objects to build configuration section and elements, and those allow some settings related to the merging (like setting the appropriate ConfigurationElementCollectionType for example). Are these related to only merging with machine.config (or multiple layers of web.config files in a web application), or is it possible to manually trigger the merging of pre-loaded config files?


Note: I would appreciate better a solution that would work on .NET 3.0+. Please add a note if your answer targets a higher version of the framework.

What is the DNVM?

Im playing with the new VsCode editor, and created an ASPNET 5 template project. To restore the packages, I found in the tutorials that I need to run the dnu restore command, which gets all the server side references that I need.

After that, to build it I must run the dnx: web or kestrel command, and everything goes as expected.

But, what are those tools? In the git repository of the DNVM we dont have much information about it.

Does the dnu restore uses the nuget?

Someone have some complete documentation about all that in the new .NET?

I would like to know too if its possible to use the Roslyn compiler within the VSCode on Windows 8.1.

Text vanishing in Winforms Textbox

I'm running into a strange issue with a WinForms textbox. When I set the Text property to a long string, the text seems to vanish. My understanding is that a textbox in Winforms has a default MaxLength of 32767, which can be set to any value less than or equal to int.MaxValue. The steps to reproduce the issue are as follows:

  1. Fire up Visual Studio 2013
  2. Create a new Windows Form Application. Choose to target the .NET 3.5 framework.
  3. Drag a textbox control onto the form.
  4. In the form load event, type in the following code:

    private void Form1_Load(object sender, EventArgs e)
    {
        // Setting the MaxLength property should be unnecessary since the
        // default is 32767, but I'm implicitly setting it anyway.
        textBox1.MaxLength = int.MaxValue;
        string s = "";
    
        // Weird things happen when the value in the next line
        // is set to anything >= 4680
        for (int i = 0; i < 15000; i++)
        {
            s = s + "A";
        }
    
        textBox1.Text = s;
    }
    
    

Run this application and you'll that the textbox "appears" empty. I say "appears" because if you put your cursor in the textbox, you can see that it behaves as though something is in the textbox, but nothing is there visually.

Whatever is going on, 4680 seems to be the "magic number". If you change the number in the for loop to 4680, you still get no text in the textbox (although clicking in the textbox will make the text show up). If you change it to 4679 or anything smaller, then it works just fine.

Does anyone have any ideas or workarounds for this odd behavior?

Dashing.net Jobs not loading

dashing.net\Controllers\EventsController.Get() not firing after publishing to IIS web site(inetpub\wwwroot...) locally. This event is needed to load the jobs. Not sure why. It works fine in VS 2012 IDE.

why in the collection interface the index is of type int? (signed) [duplicate]

This question already has an answer here:

Why the index type for the collection allow to accept negative index if they are not implemented?

silly ex:

List students = new List();
students[-1]; // will throw an OutOfRangeException

in other languages the -1 Index mean the last element. in C# is an out of range exception.

My question is:

Why in the collection interface is not used the Uint instead of int?

Any particular reason for this design policy?

Wrapping My Head Around await async and NHibernate

Given this code:

private ISession _session;

public async Task<T> GetAsync<T>(int id) where T : ISomeEntity
{
    //how to call and return _session.Get<T>(id) asynchronous
}

Is it possible to call NHibernate ISession.Get<T>() asynchronously? Advisable? Not worth it?

Unlimited number of bullets [GameDev]

I try to make shooter game on C# with SFML.NET, but I can`t imagine how to make an ability to shoot more than 1 bullet, because now I have just one null-object of bullet-class, and when player presses Space key this object gets link to the new bullet.

So, I have the Bullet-class, null-object public static Bullet bullet = null; and condition if (Keyboard.IsKeyPressed(Keyboard.Key.Space)) {if(bullet == null) bullet = new Bullet(t, p.rect.Left, p.rect.Top, p.reverse);}

When bullet reaches the wall or enemy bullet object gets equated to null. The problem is to make ability to shoot more bullets before this bullet reaches the wall or enemy (and disappear). I think this is not a good solution to make null-objects for every possible pullet, because then we have limited amount of possible bullets.

The connection was not closed [duplicate]

This question already has an answer here:

This is doing my head in. I have tried try and catch with finally and other things but this error keeps coming back. Please some one help. My c# code:

 void show()
    {
       string str = "SELECT PID, Pname, Gender, ContactNum, Category, Department, Ward, AdmitDate, DischargeDate, NumOfDays, CostOfTest, NumOfDocsVisited, DocFee, BedCost, TotalCost, GrandTotal FROM Patient";
        cmd = new SqlCommand(str, con);
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            GridView1.DataBind();
                con.Close();
    }

error is: The connection was not closed. The connection's current state is open. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The connection was not closed. The connection's current state is open.

Source Error:

Line 50:            string str = "SELECT PID, Pname, Gender, ContactNum, Category, Department, Ward, AdmitDate, DischargeDate, NumOfDays, CostOfTest, NumOfDocsVisited, DocFee, BedCost, TotalCost, GrandTotal FROM Patient";
Line 51:             cmd = new SqlCommand(str, con);
Line 52:                 con.Open();
Line 53:                 SqlDataAdapter adp = new SqlDataAdapter(cmd);
Line 54:                 DataTable dt = new DataTable();

Stack Trace:

[InvalidOperationException: The connection was not closed. The connection's current state is open.]

System.Data.ProviderBase.DbConnectionInternal.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +14 System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource1 retry) +94 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110 System.Data.SqlClient.SqlConnection.Open() +96 SMC.Billing.show() in e:\VS2013 projects\SMC\SMC\Billing.aspx.cs:52 SMC.Billing.Button3_Click(Object sender, EventArgs e) in e:\VS2013 projects\SMC\SMC\Billing.aspx.cs:97 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628722 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103 System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

Run action and defined speed

I am trying to create a performance test in .NET and one of the steps is to "call" server at defined speed like: persistent ~400 calls per second.

The problem is that running server call has different length from: 10ms to 100ms. My first try was simple for loop with Thread.Sleep but this gives me results form 250-600 calls per second, depending on moment and server responses :(

Adapting grid with expanders to available height

I have a 'pile' of expanders on top of each other, which can be opened/closed independently.

All but one have a fixed height (when expanded). The other has a MinHeight, but I would like it to stretch to fill the remaining available height. If the combined heights of the expanders is greater than the available height, then scrollbars appear.

I've got that far using a Grid, with one expander per grid, and the row Height set to * for the stretching expander, and Auto for the others.

This works fine except in one case: if the stretchy expander is collapsed, and the combined height of the other expanders is less than the available height, then the stretching expander fills the remaining space anyway, just with it's content collapsed so I get a big blob of background colour.

I've also tried a StackPanel, or nested Grids, but haven't managed to resolve that problem without creating others.

Any ideas?

(Paste this into a Window)

<ScrollViewer>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*" MinHeight="23"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Expander IsExpanded="False" Grid.Row="0" Header="Fixed">
            <Border Background="Red" Height="200" />
        </Expander>
        <Expander IsExpanded="False" Grid.Row="1" Header="Stretchy">
            <Border Background="Blue" />
        </Expander>
        <Expander IsExpanded="False" Grid.Row="2" Header="Fixed">
            <Border Background="Green" Height="300" />
        </Expander>
    </Grid>
</ScrollViewer>

Incorrect syntaxt error when using 'IN @Ids'

I'm using Dapper, and trying to get a collection of Players using the following query:

public ICollection<Player> GetPlayersWithPointsInMatch(int id)
{
    const string sql =
                    @"SELECT
                        p.Id, 
                        p.FirstName, 
                        p.LastName, 
                        pmr.Goals, 
                        pmr.Assists 
                    FROM Players p 
                    LEFT JOIN PlayerMatchStats pmr ON p.Id = pmr.PlayerId 
                    WHERE pmr.MatchId IN @Ids
                    AND (pmr.Goals > 0 OR pmr.Assists > 0)";
    return Get<Player>(sql, new[]{id});
}

The Get method looks like this:

public ICollection<T> Get<T>(string sql, ICollection<int> ids)
{
    using (var connection = new SqlConnection(ConnectionString()))
    {
        return connection.Query<T>(sql, new { ids }).ToICollection();
    }
}

And, ToICollection looks like this:

public static ICollection<T> ToICollection<T>(this IEnumerable<T> iEnumerable)
        {
            var icollection = iEnumerable as ICollection<T>;
            return icollection ?? iEnumerable.ToArray();
        }

This is the error I'm getting on connection.Query:

Additional information: Incorrect syntax near '@Ids'.

If I run this query in SQL Management Studio, it works:

SELECT
    p.Id, 
    p.FirstName, 
    p.LastName, 
    pmr.Goals, 
    pmr.Assists 
FROM Players p 
LEFT JOIN PlayerMatchStats pmr ON p.Id = pmr.PlayerId 
WHERE pmr.MatchId IN (13)
AND (pmr.Goals > 0 OR pmr.Assists > 0)

I can't really figure out where my error is, as per my understanding the query generated by Dapper should be the same as the one I write myself in SQLMS?

Take a screenshot of a WPF window with the predefined image size without losing quality

When I take a screenshot of a current WPF window, the image resolution is that of my monitor (if the app is maximized), which is ok. However, if I was to print that image to a much bigger format, the image would look blurry. I found the way to capture the current window, and save it as a png file, but it's not doing the trick. The image is saved with the resolution I set, but the actual wpf window takes only a small portion of the saved image. Example is taken from:

http://ift.tt/1wybIDL

        var screen = System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);

        var rtb = new RenderTargetBitmap(4000, 4000, 96, 96, PixelFormats.Pbgra32);

        rtb.Render(screen);

        var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
        enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));

        using (var stm = System.IO.File.Create("ScreenShot.png"))
        {
            enc.Save(stm);
            using (Image img = Image.FromStream(stm))
            {
                Rectangle dest = new Rectangle(0, 0, 6000, 4000);

                using (Graphics imgG = Graphics.FromImage(img))
                {
                    imgG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    imgG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    imgG.DrawImage(img, dest);
                }

                img.Save("NewScreenShot.png");
            }
        }

So basically, I'd like to capture the screenshot with the resolution of 4000 x 4000, if that's possible, without losing quality. The above code produces an image of 4000 x 4000, however the screenshot only takes a small portion of it, its original resolution.

Object instantiation using Reflection works in VB.NET but not C#

I'm trying to instantiate an object from a dll without referencing it. I can do it using Reflection in VB.NET but can't figure out how to do it in C#.

In VB.NET:

Public Class Form1

Dim bytes() As Byte = System.IO.File.ReadAllBytes("\\path\directory\file.dll")
Dim assmb As System.Reflection.Assembly = System.Reflection.Assembly.Load(bytes)
Dim myDllClass As Object = assmb.CreateInstance("myNamespace.myClass")

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim conStr As String = myDllClass.publicConString
    Dim dt As DataTable = myDllClass.MethodReturnsDatatable("select * from Part", conStr)
    DataGridView1.DataSource = dt

End Sub

In C#:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    static byte[] bytes = System.IO.File.ReadAllBytes(@"\\path\directory\file.dll");
    static System.Reflection.Assembly assmb = System.Reflection.Assembly.Load(bytes);
    object myDllClass = assmb.CreateInstance("myNamespace.myClass");

    private void Form1_Load(object sender, EventArgs e)
    {
        string conStr = myDllClass.publicConString;
        DataTable dt = myDllClass.MethodReturnsDatatable("select * from Part", conStr);
        dataGridView1.DataSource = dt;
    }                
}

I get these two errors:

Error 1 'object' does not contain a definition for 'publicConString' and no extension method 'publicConString' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) C:\Users\Username\Desktop\C#\FormTest\FormTest\Form1.cs 29 34 FormTest

Error 2 'object' does not contain a definition for 'MethodReturnsDatatable' and no extension method 'MethodReturnsDatatable' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) C:\Users\Username\Desktop\C#\FormTest\FormTest\Form1.cs 30 33 FormTest

Any insight?

Thanks in advance.