Programs & Examples On #Gallio

Gallio is an Automation Platform for .NET

To get specific part of a string in c#

To avoid getting expections at run time , do something like this.

There are chances of having empty string sometimes,

string a = "abc,xyz,wer";
string b=string.Empty;

if(!string.IsNullOrEmpty(a ))
{
  b = a.Split(',')[0];
}

How do I check if a Key is pressed on C++

There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.

Solution for linux and other posix compliant systems:

Here, for Morgan Mattews's code provide kbhit() functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.

Solution for windows:

For windows, Microsoft offers _kbhit()

jQuery set checkbox checked

You can write like below given code.

HTML

<input type="checkbox"  id="estado_cat" class="ibtn">

jQuery

$(document).ready(function(){
    $(".ibtn").click(function(){
        $(".ibtn").attr("checked", "checked");
    });
});

Hope it work for you.

How can I send an inner <div> to the bottom of its parent <div>?

Here is way to avoid absolute divs and tables if you know parent's height:

<div class="parent">
    <div class="child"> <a href="#">Home</a>
    </div>
</div>

CSS:

.parent {
    line-height:80px;
    border: 1px solid black;
}
.child {
    line-height:normal;
    display: inline-block;
    vertical-align:bottom;
    border: 1px solid red;
}

JsFiddle:

Example

IIS7 URL Redirection from root to sub directory

I could not get this working with the accepted answer, mainly because I did not know where to enter that code. I looked everywhere for some explanation of the URL Rewrite tool that made sense, but could not find any. I ended up using the HTTP Redirect tool in IIS.

  1. Choose your site
  2. Click HTTP Redirect in the IIS section (Make sure the Role Service is installed)
  3. Check "Redirect requests to this destination"
  4. Enter where you want to redirect. In your case "wwww.mysite.com/menu_1/MainScreen.aspx"
  5. In Redirect Behavior, I found I had to check "Only redirect requests to content in this directory (not subdirectories), or it would go into a loop. See what works for you.

Hope this helps.

How to upgrade Angular CLI project?

According to the documentation on here http://angularjs.blogspot.co.uk/2017/03/angular-400-now-available.html you 'should' just be able to run...

npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save

I tried it and got a couple of errors due to my zone.js and ngrx/store libraries being older versions.

Updating those to the latest versions npm install zone.js@latest --save and npm install @ngrx/store@latest -save, then running the angular install again worked for me.

How to assign Php variable value to Javascript variable?

Put quotes around the <?php echo $cname; ?> to make sure Javascript accepts it as a string, also consider escaping.

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

The response is a bit late - but in case anyone has the issue in the future...

From the screenshot above - it seems that you are adding the url data (username, password, grant_type) to the header and not to the body element.

Clicking on the body tab, and then select "x-www-form-urlencoded" radio button, there should be a key-value list below that where you can enter the request data

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Further reading for any of the topics here: The Definitive Guide to Linux System Calls


I verified these using GNU Assembler (gas) on Linux.

Kernel Interface

x86-32 aka i386 Linux System Call convention:

In x86-32 parameters for Linux system call are passed using registers. %eax for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.

The return value is in %eax. All other registers (including EFLAGS) are preserved across the int $0x80.

I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.

If there are more than six arguments, %ebx must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.

For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80: Hello, world in assembly language with Linux system calls?

There is a faster way to make 32-bit system calls: using sysenter. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80. You should normally call into the vDSO instead of using sysenter directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter, and everything else to do with system calls.)

x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:

Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80

http://www.int80h.org/bsdasm/#default-calling-convention


x86-64 Linux System Call convention:

(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)

Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)

Here is the snippet from this section:

  1. User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
  2. A system-call is done via the syscall instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.
  3. The number of the syscall has to be passed in register %rax.
  4. System-calls are limited to six arguments, no argument is passed directly on the stack.
  5. Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is -errno.
  6. Only values of class INTEGER or class MEMORY are passed to the kernel.

Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)

This 32-bit int $0x80 ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.

User Interface: function calling

x86-32 Function Calling convention:

In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.

Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp before a call, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double or something.

Some other modern 32-bit systems still don't require more than 4 byte stack alignment.


x86-64 System V user-space Function Calling convention:

x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).

In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.

For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:

Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:

  1. If the class is MEMORY, pass the argument on the stack.
  2. If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used

So %rdi, %rsi, %rdx, %rcx, %r8 and %r9 are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call instruction should be given. The stack (%rsp) must be 16B-aligned when call executes.

If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)

The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)

Variadic functions (like printf) always need %al = the number of FP register args.

There are rules for when to pack structs into registers (rdx:rax on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.


Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.

Smooth GPS data

One method that uses less math/theory is to sample 2, 5, 7, or 10 data points at a time and determine those which are outliers. A less accurate measure of an outlier than a Kalman Filter is to to use the following algorithm to take all pair wise distances between points and throw out the one that is furthest from the the others. Typically those values are replaced with the value closest to the outlying value you are replacing

For example

Smoothing at five sample points A, B, C, D, E

ATOTAL = SUM of distances AB AC AD AE

BTOTAL = SUM of distances AB BC BD BE

CTOTAL = SUM of distances AC BC CD CE

DTOTAL = SUM of distances DA DB DC DE

ETOTAL = SUM of distances EA EB EC DE

If BTOTAL is largest you would replace point B with D if BD = min { AB, BC, BD, BE }

This smoothing determines outliers and can be augmented by using the midpoint of BD instead of point D to smooth the positional line. Your mileage may vary and more mathematically rigorous solutions exist.

How to compare timestamp dates with date-only parameter in MySQL?

Use a conversion function of MYSQL :

SELECT * FROM table WHERE DATE(timestamp) = '2012-05-05' 

This should work

Creating a dynamic choice field

If you need a dynamic choice field in django admin; This works for django >=2.1.

class CarAdminForm(forms.ModelForm):
    class Meta:
        model = Car

    def __init__(self, *args, **kwargs):
        super(CarForm, self).__init__(*args, **kwargs)

        # Now you can make it dynamic.
        choices = (
            ('audi', 'Audi'),
            ('tesla', 'Tesla')
        )

        self.fields.get('car_field').choices = choices

    car_field = forms.ChoiceField(choices=[])

@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
    form = CarAdminForm

Hope this helps.

Proxies with Python 'Requests' module

You can refer to the proxy documentation here.

If you need to use a proxy, you can configure individual requests with the proxies argument to any request method:

import requests

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "https://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

To use HTTP Basic Auth with your proxy, use the http://user:[email protected]/ syntax:

proxies = {
    "http": "http://user:[email protected]:3128/"
}

Convert boolean result into number/integer

if you want integer x value change if 1 to 0 and if 0 to 1 you can use (x + 1) % 2

How to run a jar file in a linux commandline

Running a from class inside your JAR file load.jar is possible via

java -jar load.jar

When doing so, you have to define the application entry point. Usually this is done by providing a manifest file that contains the Main-Class tag. For documentation and examples have a look at this page. The argument load=2 can be supplied like in a normal Java applications:

java -jar load.jar load=2

Having also the current directory contained in the classpath, required to also make use of the Class-Path tag. See here for more information.

Bootstrap: How do I identify the Bootstrap version?

The Bootstrap version will be stated at the top of the CSS file. Simply open it and look at the top of the file.

e.g.

/*!
 * Bootstrap v2.3.0
 *
 * Copyright 2012 Twitter, Inc
 * Licensed under the Apache License v2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Designed and built with all the love in the world @twitter by @mdo and @fat.
 */

Error handling with PHPMailer

$mail = new PHPMailer();

$mail->AddAddress($email); 
$mail->From     = $from;
$mail->Subject  = $subject; 
$mail->Body     = $body;

if($mail->Send()){
    echo 'Email Successfully Sent!';
}else{
    echo 'Email Sending Failed!';
}

the simplest way to handle email sending successful or failed...

Different names of JSON property during serialization and deserialization

They must have included this as a feature, because now setting a different @JsonProperty for a getter and setter results in exactly what you would expect (different property name during serialization and deserialization for the same field). Jackson version 2.6.7

Creating composite primary key in SQL Server

How about something like

CREATE TABLE testRequest (
        wardNo nchar(5),
        BHTNo nchar(5),
        testID nchar(5),
        reqDateTime datetime,
        PRIMARY KEY (wardNo, BHTNo, testID)
);

Have a look at this example

SQL Fiddle DEMO

Event binding on dynamically created elements?

You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:

function addCallbacks(eles){
    eles.hover(function(){alert("gotcha!")});
}

$(document).ready(function(){
    addCallbacks($(".myEles"))
});

// ... add elements ...
addCallbacks($(".myNewElements"))

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.

HTML

<li>
    <a id="byParameter" 
       class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
           presence of parameter</a>
</li>

Controller

@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
    //Perform logic with foo
    return "Mapped by path + method + presence of query parameter! (MappingController)";
}

Spring URI Template Documentation

VBA: Counting rows in a table (list object)

You can use:

Sub returnname(ByVal TableName As String)

MsgBox (Range("Table15").Rows.count)

End Sub

and call the function as below

Sub called()

returnname "Table15"

End Sub

Python urllib2 Basic Auth Problem

(copy-paste/adapted from https://stackoverflow.com/a/24048772/1733117).

First you can subclass urllib2.BaseHandler or urllib2.HTTPBasicAuthHandler, and implement http_request so that each request has the appropriate Authorization header.

import urllib2
import base64

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

Then if you are lazy like me, install the handler globally

api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"

auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
    realm=None, # default realm.
    uri=api_url,
    user=api_username,
    passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

Yes lists and tuples are always ordered while dictionaries are not

What is the preferred/idiomatic way to insert into a map?

In short, [] operator is more efficient for updating values because it involves calling default constructor of the value type and then assigning it a new value, while insert() is more efficient for adding values.

The quoted snippet from Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers, Item 24 might help.

template<typename MapType, typename KeyArgType, typename ValueArgType>
typename MapType::iterator
insertKeyAndValue(MapType& m, const KeyArgType&k, const ValueArgType& v)
{
    typename MapType::iterator lb = m.lower_bound(k);

    if (lb != m.end() && !(m.key_comp()(k, lb->first))) {
        lb->second = v;
        return lb;
    } else {
        typedef typename MapType::value_type MVT;
        return m.insert(lb, MVT(k, v));
    }
}

You may decide to choose a generic-programming-free version of this, but the point is that I find this paradigm (differentiating 'add' and 'update') extremely useful.

Assigning a variable NaN in python without numpy

nan = float('nan')

And now you have the constant, nan.

You can similarly create NaN values for decimal.Decimal.:

dnan = Decimal('nan')

How to add a default "Select" option to this ASP.NET DropDownList control?

If you do an "Add" it will add it to the bottom of the list. You need to do an "Insert" if you want the item added to the top of the list.

How do I capture all of my compiler's output to a file?

Based on an earlier reply by @dmckee

make | tee makelog.txt

This gives you real-time scrolling output while compiling, and simultaneously write to the makelog.txt file.

Embedding JavaScript engine into .NET

Try Javascript .NET. It is hosted on GitHub It was originally hosted on CodePlex, here)

Project discussions: http://javascriptdotnet.codeplex.com/discussions

It implements Google V8. You can compile and run JavaScript directly from .NET code with it, and supply CLI objects to be used by the JavaScript code as well. It generates native code from JavaScript.

How do I force my .NET application to run as administrator?

I implemented some code to do it manually:

using System.Security.Principal;
public bool IsUserAdministrator()
{
    bool isAdmin;
    try
    {
        WindowsIdentity user = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(user);
        isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
    catch (UnauthorizedAccessException ex)
    {
        isAdmin = false;
    }
    catch (Exception ex)
    {
        isAdmin = false;
    }
    return isAdmin;
}

Hide div if screen is smaller than a certain width

The problem I was having is my css media queries and my IF statement in Jquery clashing. They were both set to 700px but one would think it's hit 700px before the other.

To get around this I created a empty Div right at the top of my HTML(outside my main container)

<div id="max-width"></div>

In css I set this div to display none

 #max-width {
        display: none;
    }

In my JS created a function

var hasSwitched = function () {
    var maxWidth = parseInt($('#max-width').css('max-width'), 10);
    return !isNaN(maxWidth);
};

So in my IF statement instead of saying if (hasSwitched<700) perform the following code, I did the following

if (!hasSwitched()) { Your code

}

else{ your code

}

By doing this CSS tells Jquery when it's hit 700px. So css and jquery are both synchronized... rather than having a couple of pixels difference. Do give this a try peeps it shall definitely not disappoint.

To get this same logic working for IE8 I used the Respond.js plugin(which also definitely works) It lets you use media queries for IE8. Only thing that wasn't supported was the viewport width and viewport height... hence my reason to try get my css and JS working together. Hope this helps you guys

Instance member cannot be used on type

Another example is, you have class like :

@obc class Album: NSObject {
    let name:String
    let singer:Singer
    let artwork:URL
    let playingSong:Song


    // ...

    class func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
        // ...
       return playingSong.lyric
    }
}

you will also get the same type of error like :

instance member x cannot be used on type x. 

It's because you assign your method with "class" keyword (which makes your method a type method) and using like :

Album.getCurrentlyPlayingSongLyric(duration: 5)

but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :

 // ...

 func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
        // ...
       return playingSong.lyric
 }

 // ...

Now you're free to go.

How to clear an ImageView in Android?

I tried to remove the Image of the ImageView too by using ImageView.setImageRessource(0) but it didn't work for me.
Luckily I got this message in the logs:

Caused by: java.lang.IllegalStateException: The specified child already has a parent. 
You must call removeView() on the child's parent first.

So let's say, layoutmanager is your instance for the layout, than you need to do that:

RelativeLayout layoutManager = new RelativeLayout(this);
ImageView image = new ImageView(this);

// this line worked for me
layoutManager.removeView(image);

How to get ID of the last updated row in MySQL?

If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.

If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.

Having set this, you can then use a query like: SELECT id FROM table ORDER BY last_modified DESC LIMIT 1; to get the most recently modified row.

Xampp-mysql - "Table doesn't exist in engine" #1932

For me I removed whole data folder from xampp\mysql\ and pasted data folder of previous one here which solved my problem...

Injecting Mockito mocks into a Spring bean

If you're using Spring Boot 1.4, it has an awesome way of doing this. Just use new brand @SpringBootTest on your class and @MockBean on the field and Spring Boot will create a mock of this type and it will inject it into the context (instead of injecting the original one):

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {

    @MockBean
    private RemoteService remoteService;

    @Autowired
    private Reverser reverser;

    @Test
    public void exampleTest() {
        // RemoteService has been injected into the reverser bean
        given(this.remoteService.someCall()).willReturn("mock");
        String reverse = reverser.reverseSomeCall();
        assertThat(reverse).isEqualTo("kcom");
    }

}

On the other hand, if you're not using Spring Boot or are you using a previous version, you'll have to do a bit more work:

Create a @Configuration bean that injects your mocks into Spring context:

@Configuration
@Profile("useMocks")
public class MockConfigurer {

    @Bean
    @Primary
    public MyBean myBeanSpy() {
        return mock(MyBean.class);
    }
}

Using @Primary annotation you're telling spring that this bean has priority if no qualifier are specified.

Make sure you annotate the class with @Profile("useMocks") in order to control which classes will use the mock and which ones will use the real bean.

Finally, in your test, activate userMocks profile:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebIntegrationTest
@ActiveProfiles(profiles={"useMocks"})
public class YourIntegrationTestIT {

    @Inject
    private MyBean myBean; //It will be the mock!


    @Test
    public void test() {
        ....
    }
}

If you don't want to use the mock but the real bean, just don't activate useMocks profile:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebIntegrationTest
public class AnotherIntegrationTestIT {

    @Inject
    private MyBean myBean; //It will be the real implementation!


    @Test
    public void test() {
        ....
    }
}

Reading specific XML elements from XML file

You could use an XPath, too. A bit old fashioned but still effective:

using System.Xml;

...

XmlDocument xmlDocument;

xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);

foreach (XmlElement xmlElement in 
    xmlDocument.DocumentElement.SelectNodes("word[category='verb']"))
{
    Console.Out.WriteLine(xmlElement.OuterXml);
}

replace String with another in java

     String s1 = "HelloSuresh";
     String m = s1.replace("Hello","");
     System.out.println(m);

Suppress warning messages using mysql from within Terminal, but password written in bash script

If you happen to use Rundeck for scheduling your tasks, or any other platform where you ask for a mylogin.cnf file, I have successfully used the following shell code to provide a new location for the file before proceeding with sql calls:

if test -f "$CUSTOM_MY_LOGINS_FILE_PATH"; then
   chmod 600 $CUSTOM_MY_LOGINS_FILE_PATH
   export MYSQL_TEST_LOGIN_FILE="$CUSTOM_MY_LOGINS_FILE_PATH"
fi

...

result=$(mysql --login-path=production -NBA -D $schema -e "$query")

Where MYSQL_TEST_LOGIN_FILE is an environment variable that can be set to a different file path than the default one.

This is especially useful if you are running in a forked process and can't move or copy files to the $HOME directory.

See documentation here.

How to make an embedded video not autoplay

A couple of wires are crossed here. The various autoplay settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.

However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.

Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)

Bootstrap: Position of dropdown menu relative to navbar item

Not sure about how other people solve this problem or whether Bootstrap has any configuration for this.

I found this thread that provides a solution:

https://github.com/twbs/bootstrap/issues/1411

One of the post suggests the use of

<ul class="dropdown-menu" style="right: 0; left: auto;">

I tested and it works.

Hope to know whether Bootstrap provides config for doing this, not via the above css.

Cheers.

Create a one to many relationship using SQL Server

  1. Define two tables (example A and B), with their own primary key
  2. Define a column in Table A as having a Foreign key relationship based on the primary key of Table B

This means that Table A can have one or more records relating to a single record in Table B.

If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:

ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id) 
  • fk_b: Name of the foreign key constraint, must be unique to the database
  • b_id: Name of column in Table A you are creating the foreign key relationship on
  • b: Name of table, in this case b
  • id: Name of column in Table B

how to check if a form is valid programmatically using jQuery Validation Plugin

2015 answer: we have this out of the box on modern browsers, just use the HTML5 CheckValidity API from jQuery. I've also made a jquery-html5-validity module to do this:

npm install jquery-html5-validity

Then:

var $ = require('jquery')
require("jquery-html5-validity")($);

then you can run:

$('.some-class').isValid()

true

How do I tokenize a string in C++?

Here's a real simple one:

#include <vector>
#include <string>
using namespace std;

vector<string> split(const char *str, char c = ' ')
{
    vector<string> result;

    do
    {
        const char *begin = str;

        while(*str != c && *str)
            str++;

        result.push_back(string(begin, str));
    } while (0 != *str++);

    return result;
}

length and length() in Java

I was taught that for arrays, length is not retrieved through a method due to the following fear: programmers would just assign the length to a local variable before entering a loop (think a for loop where the conditional uses the array's length.) The programmer would supposedly do so to trim down on function calls (and thereby improve performance.) The problem is that the length might change during the loop, and the variable wouldn't.

How to export the Html Tables data into PDF using Jspdf

Just follow these steps i can assure pdf file will be generated

    <html>
    <head>

    <title>Exporting table data to pdf Example</title>


    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
    <script type="text/javascript" src="js/jspdf.js"></script>
    <script type="text/javascript" src="js/from_html.js"></script>
    <script type="text/javascript" src="js/split_text_to_size.js"></script>
    <script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
    <script type="text/javascript" src="js/cell.js"></script>
    <script type="text/javascript" src="js/FileSaver.js"></script>


    <script type="text/javascript">
        $(document).ready(function() {

            $("#exportpdf").click(function() {
                var pdf = new jsPDF('p', 'pt', 'ledger');
                // source can be HTML-formatted string, or a reference
                // to an actual DOM element from which the text will be scraped.
                source = $('#yourTableIdName')[0];

                // we support special element handlers. Register them with jQuery-style 
                // ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
                // There is no support for any other type of selectors 
                // (class, of compound) at this time.
                specialElementHandlers = {
                    // element with id of "bypass" - jQuery style selector
                    '#bypassme' : function(element, renderer) {
                        // true = "handled elsewhere, bypass text extraction"
                        return true
                    }
                };
                margins = {
                    top : 80,
                    bottom : 60,
                    left : 60,
                    width : 522
                };
                // all coords and widths are in jsPDF instance's declared units
                // 'inches' in this case
                pdf.fromHTML(source, // HTML string or DOM elem ref.
                margins.left, // x coord
                margins.top, { // y coord
                    'width' : margins.width, // max width of content on PDF
                    'elementHandlers' : specialElementHandlers
                },

                function(dispose) {
                    // dispose: object with X, Y of the last line add to the PDF 
                    //          this allow the insertion of new lines after html
                    pdf.save('fileNameOfGeneretedPdf.pdf');
                }, margins);
            });

        });
    </script>
    </head>
    <body>
    <div id="yourTableIdName">
        <table style="width: 1020px;font-size: 12px;" border="1">
            <thead>
                <tr align="left">
                    <th>Country</th>
                    <th>State</th>
                    <th>City</th>
                </tr>
            </thead>


            <tbody>

                <tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
<tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr><tr align="left">
                    <td>India</td>
                    <td>Telangana</td>
                    <td>Nirmal</td>
                </tr>
            </tbody>
        </table></div>

        <input type="button" id="exportpdf" value="Download PDF">


    </body>

    </html>

Output:

Html file output: html output

Pdf file output: pdf output

How to center a subview of UIView

I would use:

child.center = CGPointMake(parent.bounds.height / 2, parent.bounds.width / 2)

This is simple, short, and sweet. If you use @Hejazi's answer above and parent.center is set to anything other than (0,0) your subview will not be centered!

MySQL table is marked as crashed and last (automatic?) repair failed

I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".

  • Server type: MySQL
  • Server version: 5.7.23 - MySQL Community Server (GPL)
  • phpMyAdmin: Version information: 4.7.7

How do I change the language of moment.js?

You need moment.lang (WARNING: lang() is deprecated since moment 2.8.0, use locale() instead):

moment.lang("de").format('LLL');

http://momentjs.com/docs/#/i18n/


As of v2.8.1, moment.locale('de') sets the localization, but does not return a moment. Some examples:

var march = moment('2017-03')
console.log(march.format('MMMM')) // 'March'

moment.locale('de') // returns the new locale, in this case 'de'
console.log(march.format('MMMM')) // 'March' still, since the instance was before the locale was set

var deMarch = moment('2017-03')
console.log(deMarch.format('MMMM')) // 'März'

// You can, however, change just the locale of a specific moment
march.locale('es')
console.log(march.format('MMMM')) // 'Marzo'

In summation, calling locale on the global moment sets the locale for all future moment instances, but does not return an instance of moment. Calling locale on an instance, sets it for that instance AND returns that instance.

Also, as Shiv said in the comments, make sure you use "moment-with-locales.min.js" and not "moment.min.js", otherwise it won't work.

Media Player called in state 0, error (-38,0)

I encountered the same issue few days ago. My audio MediaPlayer works fine on devices with high processing power, but for slow devices, the media player just did not play some time and from LogCat it had many complain about called in wrong state. So I resolved it by calling putting the call to start(), pause(),... in onPrepared() method of OnPreparedListener() as below:

mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    ........
                    mediaPlayer.start();
                    ....
                    songControlBtn.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mediaPlayer.isPlaying()) {
                                mediaPlayer.pause();

                            } else {
                                mediaPlayer.start();

                            }
                        }
                    });

                    mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            ............

                        }
                    });
                }
            });

Also try to release any media player that you do not need any more. For example, if you do not want to play the audio or video on background then you should call mediaPlayer.release() in onPause().

how to fix the issue "Command /bin/sh failed with exit code 1" in iphone

I tried restarting Xcode (7) and nothing (the have you tried switching it off and on again of iOS development for me :-)). I then tried by restarting my box and that worked.

In my case the script was failing when copying a file from a location to another one. I think it could have been related to Finder screwing with writing rights over certain folders.

How to run a shell script in OS X by double-clicking?

Alternatively, you could create a regular Mac OS X application from your script using Platypus

The remote end hung up unexpectedly while git cloning

On MacOSX High Sierra the solution for me was:

brew install git-lfs

and my repository was cloned without any errors.

How can I know when an EditText loses focus?

Implement onFocusChange of setOnFocusChangeListener and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.

 EditText txtEdit = (EditText) findViewById(R.id.edittxt);

 txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {          
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
               // code to execute when EditText loses focus
            }
        }
    });

How to wait for a JavaScript Promise to resolve before resuming function?

You can do it manually. (I know, that that isn't great solution, but..) use while loop till the result hasn't a value

kickOff().then(function(result) {
   while(true){
       if (result === undefined) continue;
       else {
            $("#output").append(result);
            return;
       }
   }
});

convert base64 to image in javascript/jquery

Have to add this based on @Joseph's answer. If someone want to create image object:

var image = new Image();
image.onload = function(){
   console.log(image.width); // image is loaded and we have image width 
}
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

Resetting a form in Angular 2 after submit

I'm using reactive forms in angular 4 and this approach works for me:

    this.profileEditForm.reset(this.profileEditForm.value);

see reset the form flags in the Fundamentals doc

Convert String XML fragment to Document Node in Java

For what it's worth, here's a solution I came up with using the dom4j library. (I did check that it works.)

Read the XML fragment into a org.dom4j.Document (note: all the XML classes used below are from org.dom4j; see Appendix):

  String newNode = "<node>value</node>"; // Convert this to XML
  SAXReader reader = new SAXReader();
  Document newNodeDocument = reader.read(new StringReader(newNode));

Then get the Document into which the new node is inserted, and the parent Element (to be) from it. (Your org.w3c.dom.Document would need to be converted to org.dom4j.Document here.) For testing purposes, I created one like this:

    Document originalDoc = 
      new SAXReader().read(new StringReader("<root><given></given></root>"));
    Element givenNode = originalDoc.getRootElement().element("given");

Adding the new child element is very simple:

    givenNode.add(newNodeDocument.getRootElement());

Done. Outputting originalDoc now yields:

<?xml version="1.0" encoding="utf-8"?>

<root>
    <given>
        <node>value</node>
    </given>
</root>

Appendix: Because your question talks about org.w3c.dom.Document, here's how to convert between that and org.dom4j.Document.

// dom4j -> w3c
DOMWriter writer = new DOMWriter();
org.w3c.dom.Document w3cDoc = writer.write(dom4jDoc);

// w3c -> dom4j
DOMReader reader = new DOMReader();
Document dom4jDoc = reader.read(w3cDoc);

(If you'd need both kind of Documents regularly, it might make sense to put these in neat utility methods, maybe in a class called XMLUtils or something like that.)

Maybe there are better ways to do this, even without any 3rd party libraries. But out of the solutions presented so far, in my view this is the easiest way, even if you need to do the dom4j <-> w3c conversions.

Update (2011): before adding dom4j dependency to your code, note that it is not an actively maintained project, and has some other problems too. Improved version 2.0 has been in the works for ages, but there's only an alpha version available. You may want to consider an alternative, like XOM, instead; read more in the question linked above.

Arrays in unix shell?

Your question asks about "unix shell scripting", but is tagged bash. Those are two different answers.

The POSIX specification for shells does not have anything to say about arrays, as the original Bourne shell did not support them. Even today, on FreeBSD, Ubuntu Linux, and many other systems, /bin/sh does not have array support. So if you want your script to work in different Bourne-compatible shells, you shouldn't use them. Alternatively, if you are assuming a specific shell, then be sure to put its full name in the shebang line, e.g. #!/usr/bin/env bash.

If you are using bash or zsh, or a modern version of ksh, you can create an array like this:

myArray=(first "second element" 3rd)

and access elements like this

$ echo "${myArray[1]}"
second element

You can get all the elements via "${myArray[@]}". You can use the slice notation ${array[@]:start:length} to restrict the portion of the array referenced, e.g. "${myArray[@]:1}" to leave off the first element.

The length of the array is ${#myArray[@]}. You can get a new array containing all the indexes from an existing array with "${!myArray[@]}".

Older versions of ksh before ksh93 also had arrays, but not the parenthesis-based notation, nor did they support slicing. You could create an array like this, though:

set -A myArray -- first "second element" 3rd 

How can I get all element values from Request.Form without specifying exactly which one with .GetValues("ElementIdName")

Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.

By the way the LINQ method also works.

A formula to copy the values from a formula to another column

Copy the cell. Paste special as link. Will update with original. No formula though.

What is the "continue" keyword and how does it work in Java?

A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.

while (getNext(line)) {
  if (line.isEmpty() || line.isComment())
    continue;
  // More code here
}

With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.

Sometimes continue is also used as a placeholder in order to make an empty loop body more clear.

for (count = 0; foo.moreData(); count++)
  continue;

The same statement without a label also exists in C and C++. The equivalent in Perl is next.

This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto. In the following example the continue will re-execute the empty for (;;) loop.

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;

How do I turn a String into a InputStreamReader in java?

Same question as @Dan - why not StringReader ?

If it has to be InputStreamReader, then:

String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);

preventDefault() on an <a> tag

It's suggested that you do not use return false, as 3 things occur as a result:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

So in this type of situation, you should really only use event.preventDefault();

Archive of article - jQuery Events: Stop (Mis)Using Return False

How to create a listbox in HTML without allowing multiple selection?

Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want

you may want to check this site

http://www.htmlcodetutorial.com/forms/_SELECT.html

What are the uses of "using" in C#?

Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.

This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.

UTF-8 in Windows 7 CMD

This question has been already answered in Unicode characters in Windows command line - how?

You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

CSS Cell Margin

margin does not work unfortunately on individual cells, however you could add extra columns between the two cells you want to put a space between... another option is to use a border with the same colour as the background...

Unexpected token ILLEGAL in webkit

It won't be exactly refering to the given problem, but I wanna share my mistake here, maybe some1 will make simmilar one and will also land with his/her problem here:

Ive got Unexpected token ILLEGAL error because I named a function with a number as 1st char.

It was 3x3check(). Changing it to check3x3() solved my problem.

Access host database from a docker container

If you want access to a Docker container where there is a DB, you have to add a bash:

docker exec -it postgresql bash

postgresql is the container name.

Once inside, from the bash, access to DB e.g:

$psql -U postgres

What is callback in Android?

It was discussed before here.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

Validate that a string is a positive integer

Just to build on VisioN's answer above, if you are using the jQuery validation plugin you could use this:

$(document).ready(function() {
    $.validator.addMethod('integer', function(value, element, param) {
        return (value >>> 0 === parseFloat(value) && value > 0);
    }, 'Please enter a non zero integer value!');
}

Then you could use in your normal rules set or add it dynamically this way:

$("#positiveIntegerField").rules("add", {required:true, integer:true});

Official reasons for "Software caused connection abort: socket write error"

In the situation explained below, client side will throw such an exception:

The server is asked to authenticate client certificate, but the client provides a certificate which Extended Key Usage doesn't support client auth, so the server doesn't accept the client's certificate, and then it closes the connection.

Throw HttpResponseException or return Request.CreateErrorResponse?

I want to point out that it has been my experience that if throwing an HttpResponseException instead of returning an HttpResponseMessage in a webapi 2 method, that if a call is made immediately to IIS Express it will timeout or return a 200 but with a html error in the response. Easiest way to test this is to make $.ajax call to a method that throws a HttpResponseException and in the errorCallBack in ajax make an immediate call to another method or even a simple http page. You will notice the imediate call will fail. If you add a break point or a settimeout() in the error call back to delay the second call a second or two giving the server time to recover it works correctly. This makes no since but its almost like the throw HttpResponseException causes the server side listener thread to exit and restart causing a split second of no server accepting connections or something.

Update: The root cause of the wierd Ajax connection Timeout is if an ajax call is made quick enough the same tcp connection is used. I was raising a 401 error ether by returning a HttpResonseMessage or throwing a HTTPResponseException which was returned to the browser ajax call. But along with that call MS was returning a Object Not Found Error because in Startup.Auth.vb app.UserCookieAuthentication was enabled so it was trying to return intercept the response and add a redirect but it errored with Object not Instance of an Object. This Error was html but was appended to the response after the fact so only if the ajax call was made quick enough and the same tcp connection used did it get returned to the browser and then it got appended to the front of the next call. For some reason Chrome just timedout, fiddler pucked becasue of the mix of json and htm but firefox rturned the real error. So wierd but packet sniffer or firefox was the only way to track this one down.

Also it should be noted that if you are using Web API help to generate automatic help and you return HttpResponseMessage then you should add a

[System.Web.Http.Description.ResponseType(typeof(CustomReturnedType))] 

attribute to the method so the help generates correctly. Then

return Request.CreateResponse<CustomReturnedType>(objCustomeReturnedType) 

or on error

return Request.CreateErrorResponse( System.Net.HttpStatusCode.InternalServerError, new Exception("An Error Ocurred"));

Hope this helps someone else who may be getting random timeout or server not available immediately after throwing a HttpResponseException.

Also returning an HttpResponseException has the added benefit of not causing Visual Studio to break on an Un-handled exception usefull when the error being returned is the AuthToken needs to be refreshed in a single page app.

Update: I am retracting my statement about IIS Express timing out, this happened to be a mistake in my client side ajax call back it turns out since Ajax 1.8 returning $.ajax() and returning $.ajax.().then() both return promise but not the same chained promise then() returns a new promise which caused the order of execution to be wrong. So when the then() promise completed it was a script timeout. Weird gotcha but not an IIS express issue a problem between the Keyboard and chair.

Scaling an image to fit on canvas

Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

The second rectangle will be the destination size (what source rectangle will be scaled to).

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas

What does "make oldconfig" do exactly in the Linux kernel makefile?

Updates an old config with new/changed/removed options.

Truncate a string straight JavaScript

Following code truncates a string and will not split words up, and instead discard the word where the truncation occurred. Totally based on Sugar.js source.

function truncateOnWord(str, limit) {
        var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
        var reg = new RegExp('(?=[' + trimmable + '])');
        var words = str.split(reg);
        var count = 0;
        return words.filter(function(word) {
            count += word.length;
            return count <= limit;
        }).join('');
    }

How to set a reminder in Android?

You can use AlarmManager in coop with notification mechanism Something like this:

Intent intent = new Intent(ctx, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
// time of of next reminder. Unix time.
long timeMs =...
if (Build.VERSION.SDK_INT < 19) {
    am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
} else {
    am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
}

It starts alarm.

public class ReminderBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
                .setSmallIcon(...)
                .setContentTitle(..)
                .setContentText(..);
        Intent intentToFire = new Intent(context, Activity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentToFire, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pendingIntent);
        NotificationManagerCompat.from(this);.notify((int) System.currentTimeMillis(), builder.build());
    }
}

Generate MD5 hash string with T-SQL

Solution:

SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)

Stop mouse event propagation

Calling stopPropagation on the event prevents propagation: 

(event)="doSomething($event); $event.stopPropagation()"

For preventDefault just return false

(event)="doSomething($event); false"

Event binding allows to execute multiple statements and expressions to be executed sequentially (separated by ; like in *.ts files.
The result of last expression will cause preventDefault to be called if falsy. So be cautious what the expression returns (even when there is only one)

How to create an empty R vector to add new items

As pointed out by Brani, vector() is a solution, e.g.

newVector <- vector(mode = "numeric", length = 50)

will return a vector named "newVector" with 50 "0"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.

aVector <- c(aVector, newScalar)

Angular routerLink does not navigate to the corresponding component

don't forget this to add this below in your template:

<router-outlet></router-outlet>

Oracle SQL Developer: Unable to find a JVM

The secret is you need to copy msvcr100.dll to the path where the installation says msvcr100.dll is missing (dialog box) and then try to install the sql developer.

For me I had to create bin folder in

C:\sqldeveloper\jdk\bin

and Copy msvcr100.dll to it.

If still not working! Try this!

You might also need to change the config file settings found in

C:\sqldeveloper\sqldeveloper\bin

Download and install 32 bit JDK (Windows) and set the path in config file as

SetJavaHome C:/Program Files (x86)/Java/jdk1.7.0_01

Test if numpy array contains only zeros

If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.

try: # removes output noise for empty slice 
    mean = np.mean(array)
except:
    mean = 0

JavaScript alert box with timer

tooltips can be used as alerts. These can be timed to appear and disappear.

CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.

Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.

variable is not declared it may be inaccessible due to its protection level

I got this error briefly after renaming the App_Code folder. Actually, I accidentally dragged the whole folder to the App_data folder. VS 2015 didn't complain it was difficult to spot what had gone wrong.

How to get HttpClient returning status code and response body?

You can avoid the BasicResponseHandler, but use the HttpResponse itself to get both status and response as a String.

HttpResponse response = httpClient.execute(get);

// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();

// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());

Why is "cursor:pointer" effect in CSS not working

Position the element as relative and then use z-index, it worked for me :)

Xcode "Build and Archive" from command line

I found how to automate the build and archive process from the comand line, I just wrote a blog article explaining how you can achieve that.

The command you have to use is xcrun:

/usr/bin/xcrun -sdk iphoneos PackageApplication \
-v "${RELEASE_BUILDDIR}/${APPLICATION_NAME}.app" \
-o "${BUILD_HISTORY_DIR}/${APPLICATION_NAME}.ipa" \
--sign "${DEVELOPER_NAME}" \
--embed "${PROVISONING_PROFILE}"

You will find all the details in the article. If you have any questions dont hesitate to ask.

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

I also faced the same issue with a self signed certificate . By referring to few of the above solutions , i tried regenerating the certificate with the correct CN i.e the IP Address of the server .But still it didn't work for me . Finally i tried regenerating the certificate by adding the SAN address to it via the below mentioned command

**keytool -genkey -keyalg RSA -keystore keystore.jks -keysize 2048 -alias <IP_ADDRESS> -ext san=ip:<IP_ADDRESS>**

After that i started my server and downloaded the client certificates via the below mentioned openssl command

**openssl s_client -showcerts -connect <IP_ADDRESS>:443 < /dev/null | openssl x509 -outform PEM > myCert.pem**

Then i imported this client certificate to the java default keystore file (cacerts) of my client machine by the below mentioned command

**keytool -import -trustcacerts -keystore /home/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.242.b08-1.el7.x86_64/jre/lib/security/cacerts -alias <IP_ADDRESS> -file ./mycert.pem**

How to escape apostrophe (') in MySql?

Replace the string

value = value.replace(/'/g, "\\'");

where value is your string which is going to store in your Database.

Further,

NPM package for this, you can have look into it

https://www.npmjs.com/package/mysql-apostrophe

Exception is never thrown in body of corresponding try statement

Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.

What's the strangest corner case you've seen in C# or .NET?

I found a second really strange corner case that beats my first one by a long shot.

String.Equals Method (String, String, StringComparison) is not actually side effect free.

I was working on a block of code that had this on a line by itself at the top of some function:

stringvariable1.Equals(stringvariable2, StringComparison.InvariantCultureIgnoreCase);

Removing that line lead to a stack overflow somewhere else in the program.

The code turned out to be installing a handler for what was in essence a BeforeAssemblyLoad event and trying to do

if (assemblyfilename.EndsWith("someparticular.dll", StringComparison.InvariantCultureIgnoreCase))
{
    assemblyfilename = "someparticular_modified.dll";
}

By now I shouldn't have to tell you. Using a culture that hasn't been used before in a string comparison causes an assembly load. InvariantCulture is not an exception to this.

Pass a datetime from javascript to c# (Controller)

I found that I needed to wrap my datetime string like this:

"startdate": "\/Date(" + date() + ")\/"

Took me an hour to figure out how to enable the WCF service to give me back the error message which told me that XD

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

I have a solution to a problem that may also apply to you. My database was in a state where a DROP TABLE failed because it couldn't find the table... but a CREATE TABLE also failed because MySQL thought the table existed. (This state could easily mess with your IF NOT EXISTS clause).

I eventually found this solution:

sudo mysqladmin flush-tables

For me, without the sudo, I got the following error:

mysqladmin: refresh failed; error: 'Access denied; you need the RELOAD privilege for this operation'

(Running on OS X 10.6)

Using ChildActionOnly in MVC

You would use it if you are using RenderAction in any of your views, usually to render a partial view.

The reason for marking it with [ChildActionOnly] is that you need the controller method to be public so you can call it with RenderAction but you don't want someone to be able to navigate to a URL (e.g. /Controller/SomeChildAction) and see the results of that action directly.

Closing Applications

for me best solotion this is

 Thread.CurrentThread.Abort();

and force close app.

Double border with different color

You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:

_x000D_
_x000D_
.triple-border:after {_x000D_
    content: " ";_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
    background: #FFE962;_x000D_
    height: 9px;_x000D_
    padding-bottom: 8px;_x000D_
    border-bottom: 9px solid #A3C662;_x000D_
    box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
_x000D_
_x000D_

You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.

Yes/No message box using QMessageBox

QT can be as simple as that of Windows. The equivalent code is

if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, "title", "Question", QMessageBox::Yes|QMessageBox::No).exec()) 
{

}

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

  1. Set the path to restore the file.
  2. Click "Options" on the left hand side.
  3. Uncheck "Take tail-log backup before restoring"
  4. Tick the check box - "Close existing connections to destination database". enter image description here
  5. Click OK.

Return HTML content as a string, given URL. Javascript Function

In some websites, XMLHttpRequest may send you something like <script src="#"></srcipt>. In that case, try using a HTML document like the script under:

<html>
  <body>
    <iframe src="website.com"></iframe>
    <script src="your_JS"></script>
  </body>
</html>

Now you can use JS to get some text out of the HTML, such as getElementbyId.

But this may not work for some websites with cross-domain blocking.

How can I delete a service in Windows?

Use the SC command, like this (you need to be on a command prompt to execute the commands in this post):

SC STOP shortservicename
SC DELETE shortservicename

Note: You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". Note to PowerShell users: sc is aliased to set-content. So sc delete service will actually create a file called delete with the content service. To do this in Powershell, use sc.exe delete service instead


If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:

SC QUERY state= all >"C:\Service List.txt"

For a more concise list, execute this command:

SC QUERY state= all | FIND "_NAME"

The short service name will be listed just above the display name, like this:

SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service

And thus to delete that service:

SC STOP MyService
SC DELETE MyService

Each for object?

_x000D_
_x000D_
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
  console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

//output
a: 1
b: 2

Difference between multitasking, multithreading and multiprocessing?

Multiprogramming: More than one task/program/job/process can reside into the main memory at one point of time. This ability of the OS is called multiprogramming.

Multitasking: More than one task/program/job/process can reside into the same CPU at one point of time. This ability of the OS is called multitasking.

How to concat string + i?

You can concatenate strings using strcat. If you plan on concatenating numbers as strings, you must first use num2str to convert the numbers to strings.

Also, strings can't be stored in a vector or matrix, so f must be defined as a cell array, and must be indexed using { and } (instead of normal round brackets).

f = cell(N, 1);
for i=1:N
   f{i} = strcat('f', num2str(i));
end

MySQL JOIN the most recent row only?

If you are working with heavy queries, you better move the request for the latest row in the where clause. It is a lot faster and looks cleaner.

SELECT c.*,
FROM client AS c
LEFT JOIN client_calling_history AS cch ON cch.client_id = c.client_id
WHERE
   cch.cchid = (
      SELECT MAX(cchid)
      FROM client_calling_history
      WHERE client_id = c.client_id AND cal_event_id = c.cal_event_id
   )

Replacing all non-alphanumeric characters with empty strings

public static void main(String[] args) {
    String value = " Chlamydia_spp. IgG, IgM & IgA Abs (8006) ";

    System.out.println(value.replaceAll("[^A-Za-z0-9]", ""));

}

output: ChlamydiasppIgGIgMIgAAbs8006

Github: https://github.com/AlbinViju/Learning/blob/master/StripNonAlphaNumericFromString.java

Adding Lombok plugin to IntelliJ project

I just found how.

I delete the first occurrence of lombok @Slf4j or log where the compiler complains, and wait for the warning(the red bubble) of IDEA, suggesting "add the lombok.extern.Slf4j.jar to classpath". Since then all goes well. It seems IDEA likes to complain about lombok.

Concatenate a NumPy array to another NumPy array

Well, the error message says it all: NumPy arrays do not have an append() method. There's a free function numpy.append() however:

numpy.append(M, a)

This will create a new array instead of mutating M in place. Note that using numpy.append() involves copying both arrays. You will get better performing code if you use fixed-sized NumPy arrays.

Git: Pull from other remote

upstream in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add. Depending on what you select for this name, your git pull usage will change. For example, if you use:

git remote add upstream git://github.com/somename/original-project.git

then you would use this to pull changes:

git pull upstream master

But, if you choose origin for the name of the remote repo, your commands would be:

To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git

And to pull: git pull origin master

Understanding the basics of Git and GitHub

  1. What is the difference between Git and GitHub?

    Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.

    GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.

  2. Is Git saving every repository locally (in the user's machine) and in GitHub?

    No, it's only local. You can decide to push (publish) some branches on GitHub.

  3. Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?

    Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.

  4. How does Git compare to a backup system such as Time Machine?

    It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.

  5. Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?

    Yes, committing and pushing are both manual.

  6. If are not collaborating and you are already using a backup system why would you use Git?

    • If you encounter an error between commits you can use the command git diff to see the differences between the current code and the last working commit, helping you to locate your error.

    • You can also just go back to the last working commit.

    • If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.

    • You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.

Make sure you check gitimmersion.com.

How to parse a query string into a NameValueCollection in .NET

There's a built-in .NET utility for this: HttpUtility.ParseQueryString

// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)

You may need to replace querystring with new Uri(fullUrl).Query.

Pass by Reference / Value in C++

When passing by value:

void func(Object o);

and then calling

func(a);

you will construct an Object on the stack, and within the implementation of func it will be referenced by o. This might still be a shallow copy (the internals of a and o might point to the same data), so a might be changed. However if o is a deep copy of a, then a will not change.

When passing by reference:

void func2(Object& o);

and then calling

func2(a);

you will only be giving a new way to reference a. "a" and "o" are two names for the same object. Changing o inside func2 will make those changes visible to the caller, who knows the object by the name "a".

Replace Default Null Values Returned From Left Outer Join

In case of MySQL or SQLite the correct keyword is IFNULL (not ISNULL).

 SELECT iar.Description, 
      IFNULL(iai.Quantity,0) as Quantity, 
      IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail', 
      iar.Compliance 
    FROM InventoryAdjustmentReason iar
    LEFT OUTER JOIN InventoryAdjustmentItem iai  on (iar.Id = iai.InventoryAdjustmentReasonId)
    LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
    LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'

Eclipse error: R cannot be resolved to a variable

I had a fully working project to which I was doing a minor change when this occured after updateting the SDK. Eclipse updated the SDK and the ADT but I could still not build the project. Exlipse said there were no further updates available.

The problem persisted until I manually uninstalled the ADT from eclipse and re-installed it. Only then would my project build. I had restarted eclipse inbetween each step.

Returning a pointer to a vector element in c++

Say, you have the following:

std::vector<myObject>::const_iterator first = vObj.begin();

Then the first object in the vector is: *first. To get the address, use: &(*first).

However, in keeping with the STL design, I'd suggest return an iterator instead if you plan to pass it around later on to STL algorithms.

What is the significance of #pragma marks? Why do we need #pragma marks?

#pragma mark is used to tag the group of methods so you may easily find and detect methods from the Jump Bar. It may help you when your code files reach about 1000 lines and you want to find methods quickly through the category from Jump box.

In a long program it becomes difficult to remember and find a method name. So pragma mark allows you to categorize methods according to the work they do. For example, you tagged some tag for Table View Protocol Methods, AlertView Methods, Init Methods, Declaration etc.

#pragma mark is the facility for XCode but it has no impact on your code. It merely helps to make it easier to find methods while coding.

How to pass query parameters with a routerLink

<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/   \______________/\_________/ \_________/ \__/
 |           |            |            |        |
scheme    authority      path        query   fragment

For more info - https://angular.io/guide/router#query-parameters-and-fragments

How to check command line parameter in ".bat" file?

I've been struggling recently with the implementation of complex parameter switches in a batch file so here is the result of my research. None of the provided answers are fully safe, examples:

"%1"=="-?" will not match if the parameter is enclosed in quotes (needed for file names etc.) or will crash if the parameter is in quotes and has spaces (again often seen in file names)

@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
rem echo First parameter is %1
if "%1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -?

starting parameter test...

Condition is true, param=-?

C:\>test.bat "-?"

starting parameter test...

Condition is false, param="-?"

Any combination with square brackets [%1]==[-?] or [%~1]==[-?] will fail in case the parameter has spaces within quotes:

@ECHO OFF
SETLOCAL 
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if [%~1]==[-?] (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat "long file name"

starting parameter test...

First parameter is "long file name"
file was unexpected at this time.

The proposed safest solution "%~1"=="-?" will crash with a complex parameter that includes text outside the quotes and text with spaces within the quotes:

@ECHO OFF
SETLOCAL 
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if "%~1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)

C:\>test.bat -source:"long file name"

starting parameter test...

First parameter is -source:"long file name"
file was unexpected at this time.

The only way to ensure all above scenarios are covered is to use EnableDelayedExpansion and to pass the parameters by reference (not by value) using variables. Then even the most complex scenario will work fine:

@ECHO OFF
SETLOCAL EnableDelayedExpansion
echo.
echo starting parameter test...
echo.
echo First parameter is %1
:: we assign the parameter to a variable to pass by reference with delayed expansion
set "var1=%~1"
echo var1 is !var1!
:: we assign the value to compare with to a second variable to pass by reference with delayed expansion
set "var2=-source:"c:\app images"\image.png"
echo var2 is !var2!
if "!var1!"=="!var2!" (echo Condition is true, param=!var1!) else (echo Condition is false, param=!var1!)
C:\>test.bat -source:"c:\app images"\image.png

starting parameter test...

First parameter is -source:"c:\app images"\image.png
var1 is -source:"c:\app images"\image.png
var2 is -source:"c:\app images"\image.png
Condition is true, param=-source:"c:\app images"\image.png

C:\>test.bat -source:"c:\app images"\image1.png

starting parameter test...

First parameter is -source:"c:\app images"\image1.png
var1 is -source:"c:\app images"\image1.png
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images"\image1.png

C:\>test.bat -source:"c:\app images\image.png"

starting parameter test...

First parameter is -source:"c:\app images\image.png"
var1 is -source:"c:\app images\image.png"
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images\image.png"

What does it mean if a Python object is "subscriptable" or not?

It basically means that the object implements the __getitem__() method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.

How prevent CPU usage 100% because of worker process in iis

I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.

Solution:

First of all find the application which is causing heavy memory usage.

You can find this in the Details section of the Task Manager.

Next.

  1. Open the IIS manager.
  2. Click on Application Pools. You'll find many application pools which your system is using.
  3. Now from the task manager you've found which application is causing the heavy memory consumption. There would be multiple options for that and you need to select the one which is having '1' in it's Application column of your web application.
  4. When you click on the application pool on the right hand side you'll see an option Advance settings under Edit Application pools. Go to Advanced Settings. 5.Now under General category set the Enable 32-bit Applications to True
  5. Restart the IIS server or you can see the consumption goes down in performance section of your Task Manager.

If this solution works for you please add a comment so that I can know.

List<object>.RemoveAll - How to create an appropriate Predicate

A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.

{
    List<Vehicle> vehicles;
    // Using a lambda
    vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
    // Using an equivalent anonymous method
    vehicles.RemoveAll(delegate(Vehicle vehicle)
    {
        return vehicle.EnquiryID == 123;
    });
    // Using an equivalent actual method
    vehicles.RemoveAll(VehiclePredicate);
}

private static bool VehiclePredicate(Vehicle vehicle)
{
    return vehicle.EnquiryID == 123;
}

Python dict how to create key or append an element to key?

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

How can I get the current user directory?

Also very helpful, while investigating the Environment.SpecialFolder enum. Use LINQPad or create a solution and execute this code:

Enum.GetValues(typeof(Environment.SpecialFolder))
    .Cast<Environment.SpecialFolder>()
    .Select(specialFolder => new
    {
        Name = specialFolder.ToString(),
        Path = Environment.GetFolderPath(specialFolder)
    })
    .OrderBy(item => item.Path.ToLower())

Folder Paths

This is the result on my machine:

MyComputer
LocalizedResources
CommonOemLinks
ProgramFiles            C:\Program Files (x86) 
ProgramFilesX86         C:\Program Files (x86) 
CommonProgramFiles      C:\Program Files (x86)\Common Files 
CommonProgramFilesX86   C:\Program Files (x86)\Common Files 
CommonApplicationData   C:\ProgramData 
CommonStartMenu         C:\ProgramData\Microsoft\Windows\Start Menu 
CommonPrograms          C:\ProgramData\Microsoft\Windows\Start Menu\Programs 
CommonAdminTools        C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools 
CommonStartup           C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup 
CommonTemplates         C:\ProgramData\Microsoft\Windows\Templates 
UserProfile             C:\Users\fisch 
LocalApplicationData    C:\Users\fisch\AppData\Local 
CDBurning               C:\Users\fisch\AppData\Local\Microsoft\Windows\Burn\Burn 
History                 C:\Users\fisch\AppData\Local\Microsoft\Windows\History 
InternetCache           C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCache 
Cookies                 C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCookies 
ApplicationData         C:\Users\fisch\AppData\Roaming 
NetworkShortcuts        C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Network Shortcuts 
PrinterShortcuts        C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Printer Shortcuts 
Recent                  C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Recent 
SendTo                  C:\Users\fisch\AppData\Roaming\Microsoft\Windows\SendTo 
StartMenu               C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu 
Programs                C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs 
AdminTools              C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools 
Startup                 C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 
Templates               C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Templates 
Desktop                 C:\Users\fisch\Desktop 
DesktopDirectory        C:\Users\fisch\Desktop 
Favorites               C:\Users\fisch\Favorites 
MyMusic                 C:\Users\fisch\Music 
MyDocuments             C:\Users\fisch\OneDrive\Documents 
MyDocuments             C:\Users\fisch\OneDrive\Documents 
MyPictures              C:\Users\fisch\OneDrive\Pictures 
MyVideos                C:\Users\fisch\Videos 
CommonDesktopDirectory  C:\Users\Public\Desktop 
CommonDocuments         C:\Users\Public\Documents 
CommonMusic             C:\Users\Public\Music 
CommonPictures          C:\Users\Public\Pictures 
CommonVideos            C:\Users\Public\Videos 
Windows                 C:\Windows 
Fonts                   C:\Windows\Fonts 
Resources               C:\Windows\resources 
System                  C:\Windows\system32 
SystemX86               C:\Windows\SysWoW64 

("fisch" is the first 5 letters of my last name. This is the user name assigned when signing in with a Microsoft Account.)

Iptables setting multiple multiports in one rule

As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.

How can I get the intersection, union, and subset of arrays in Ruby?

I assume X and Y are arrays? If so, there's a very simple way to do this:

x = [1, 1, 2, 4]
y = [1, 2, 2, 2]

# intersection
x & y            # => [1, 2]

# union
x | y            # => [1, 2, 4]

# difference
x - y            # => [4]

Source

How to make PDF file downloadable in HTML link?

if you need to limit download rate, use this code !!

<?php
$local_file = 'file.zip';
$download_file = 'name.zip';

// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);

flush();
$file = fopen($local_file, "r");
while(!feof($file))
{
    // send the current file part to the browser
    print fread($file, round($download_rate * 1024));
    // flush the content to the browser
    flush();
    // sleep one second
    sleep(1);
}
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}

?>

For more information click here

C++: Print out enum value as text

Use the preprocessor:

#define VISIT_ERROR(FIRST, MIDDLE, LAST) \
    FIRST(ErrorA) MIDDLE(ErrorB) /* MIDDLE(ErrorB2) */ LAST(ErrorC)

enum Errors
{
    #define ENUMFIRST_ERROR(E)  E=0,
    #define ENUMMIDDLE_ERROR(E) E,
    #define ENUMLAST_ERROR(E)   E
    VISIT_ERROR(ENUMFIRST_ERROR, ENUMMIDDLE_ERROR, ENUMLAST_ERROR)
    // you might undefine the 3 macros defined above
};

std::string toString(Error e)
{
    switch(e)
    {
    #define CASERETURN_ERROR(E)  case E: return #E;
    VISIT_ERROR(CASERETURN_ERROR, CASERETURN_ERROR, CASERETURN_ERROR)
    // you might undefine the above macro.
    // note that this will produce compile-time error for synonyms in enum;
    // handle those, if you have any, in a distinct macro

    default:
        throw my_favourite_exception();
    }
}

The advantage of this approach is that: - it's still simple to understand, yet - it allows for various visitations (not just string)

If you're willing to drop the first, craft yourself a FOREACH() macro, then #define ERROR_VALUES() (ErrorA, ErrorB, ErrorC) and write your visitors in terms of FOREACH(). Then try to pass a code review :).

JS jQuery - check if value is in array

You are comparing a jQuery object (jQuery('input:first')) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:

if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)

The inArray method returns -1 if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :

if(jQuery.inArray(el,arr) == -1){
    // the element is not in the array
};

Boolean vs boolean in Java

I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):

int is not boolean

Consider

    boolean bar = true;      
    System.out.printf("Bar is %b\n", bar);
    System.out.printf("Bar is %d\n", (bar)?1:0);
    int baz = 1;       
    System.out.printf("Baz is %d\n", baz);
    System.out.printf("Baz is %b\n", baz);

with output

    Bar is true
    Bar is 1
    Baz is 1
    Baz is true

Java code on 3rd line (bar)?1:0 illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of

if value \in {0,1} then cast to boolean type, otherwise throw an exception.

All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).

Bytes are not types or bits

Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).

By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).

keyword vs. type

Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class) or in other words

boolean foo = true;

vs.

Boolean foo = true;

The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).

Optimization is achieved due to trivial:

"Less runtime casting operations => more speed."

That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).

So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).

Finally, autoboxing is slower than primitives

Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.

Drawable image on a canvas

try this

Bitmap mBitmap = Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter);

protected void onDraw(Canvas canvas) {
            canvas.drawColor(0xFFAAAAAA);
            canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

        }

Negative list index?

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

ng serve not detecting file changes automatically

try this. If you do like this you don't need to fire always any command You need to fire only one time

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

cat /proc/sys/fs/inotify/max_user_watches

fs.inotify.max_user_watches=524288

android asynctask sending callbacks to ui

You can create an interface, pass it to AsyncTask (in constructor), and then call method in onPostExecute()

For example:

Your interface:

public interface OnTaskCompleted{
    void onTaskCompleted();
}

Your Activity:

public class YourActivity implements OnTaskCompleted{
    // your Activity
}

And your AsyncTask:

public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener){
        this.listener=listener;
    }

    // required methods

    protected void onPostExecute(Object o){
        // your stuff
        listener.onTaskCompleted();
    }
}

EDIT

Since this answer got quite popular, I want to add some things.

If you're a new to Android development, AsyncTask is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:

  • Possibility of memory leaks. If you keep reference to your Activity, it will stay in memory even after user left the screen (or rotated the device).
  • AsyncTask is not delivering result to Activity if Activity was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.
  • Convoluted code which does everything in Activity

When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

1) Open tool which is on top.
2) Choose options from Picklist.
3) Now Comes the popup and you can now select designers option from the list of menus on the left side.
4) Now prevent saving changes need to be unchecked that needed table re-creation. Now Click OK.

jQuery - Getting the text value of a table cell in the same row as a clicked element

You want .children() instead (documentation here):

$(this).closest('tr').children('td.two').text();

How to trap the backspace key using jQuery?

The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault(). However as the OP alluded to, if you always call it preventDefault() you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.

Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.

// Bind keydown event to this function.  Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){

    // Use jquery's constants rather than an unintuitive magic number.
    // $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
    if (e.keyCode == $.ui.keyCode.BACKSPACE) {

        // Filters out events coming from any of the following tags so Backspace
        // will work when typing text, but not take the page back otherwise.
        var rx = /INPUT|SELECT|TEXTAREA/i;
        if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
            e.preventDefault();
        }

       // Add your code here.
     }
});

Can you disable tabs in Bootstrap?

Here's my attempt. To disable a tab:

  1. Add "disabled" class to tab's LI;
  2. Remove 'data-toggle' attribute from LI > A;
  3. Suppress 'click' event on LI > A.

Code:

var toggleTabs = function(state) {
    disabledTabs = ['#tab2', '#tab3'];
    $.each(disabledTabs, $.proxy(function(idx, tabSelector) {
        tab = $(tabSelector);
        if (tab.length) {
            if (state) {
                // Enable tab click.
                $(tab).toggleClass('disabled', false);
                $('a', tab).attr('data-toggle', 'tab').off('click');
            } else {
                // Disable tab click.
                $(tab).toggleClass('disabled', true);
                $('a', tab).removeAttr('data-toggle').on('click', function(e){
                    e.preventDefault();
                });
            }
        }
    }, this));
};

toggleTabs.call(myTabContainer, true);

installing vmware tools: location of GCC binary?

Found the answer. What I did was was first

sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y

and tried it but it didn't work so I continued and did

sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`

after doing these two steps and trying again, it worked.

How to create a numpy array of all True or all False?

numpy.full((2,2), True, dtype=bool)

How to loop through all the files in a directory in c # .net?

try below code

Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)

Matplotlib scatter plot with different text at each data point

In case anyone is trying to apply the above solutions to a .scatter() instead of a .subplot(),

I tried running the following code

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.scatter(z, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

But ran into errors stating "cannot unpack non-iterable PathCollection object", with the error specifically pointing at codeline fig, ax = plt.scatter(z, y)

I eventually solved the error using the following code

plt.scatter(z, y)

for i, txt in enumerate(n):
    plt.annotate(txt, (z[i], y[i]))

I didn't expect there to be a difference between .scatter() and .subplot() I should have known better.

@Value annotation type casting to Integer from String

I had the exact same situation. It was caused by not having a PropertySourcesPlaceholderConfigurer in the Spring context, which resolves values against the @Value annotation inside of classes.

Include a property placeholder to solve the problem, no need to use Spring expressions for integers (the property file does not have to exist if you use ignore-resource-not-found="true"):

<context:property-placeholder location="/path/to/my/app.properties"
    ignore-resource-not-found="true" />

Console.WriteLine and generic List

list.ForEach(x=>Console.WriteLine(x));

convert month from name to number

An interesting look here, the code given by kelly works well,

$nmonth = date("m", strtotime($month));

but for the month of february, it won't work as expected when the current day is 30 or 31 on leap year and 29,30,31 on non-leap year.It will return 3 as month number. Ex:

$nmonth = date("m", strtotime("february"));

The solution is, add the year with the month like this:

$nmonth = date("m", strtotime("february-2012"));

I got this from this comment in php manual.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

To access Oracle from python you need (additionally) the cx_Oracle module. The module must be located either in the system python path or you have to set the PYTHONPATH appropriate.

Finding second occurrence of a substring in a string in Java

I hope I'm not late to the party.. Here is my answer. I like using Pattern/Matcher because it uses regex which should be more efficient. Yet, I think this answer could be enhanced:

    Matcher matcher = Pattern.compile("is").matcher("I think there is a smarter solution, isn't there?");
    int numOfOcurrences = 2;
    for(int i = 0; i < numOfOcurrences; i++) matcher.find();
    System.out.println("Index: " + matcher.start());

Storing images in SQL Server?

I would prefer to store the image in a directory, then store a reference to the image file in the database.

However, if you do store the image in the database, you should partition your database so the image column resides in a separate file.

You can read more about using filegroups here http://msdn.microsoft.com/en-us/library/ms179316.aspx.

How to read keyboard-input?

try

raw_input('Enter your input:')  # If you use Python 2
input('Enter your input:')      # If you use Python 3

and if you want to have a numeric value just convert it:

try:
    mode=int(raw_input('Input:'))
except ValueError:
    print "Not a number"

jQuery equivalent to Prototype array.last()

See these test cases http://jsperf.com/last-item-method The most effective way is throug .pop method (in V8), but loses the last element of the array

php - insert a variable in an echo string

Always use double quotes when using a variable inside a string and backslash any other double quotes except the starting and ending ones. You could also use the brackets like below so it's easier to find your variables inside the strings and make them look cleaner.

$var = 'my variable';
echo "I love ${var}";

or

$var = 'my variable';
echo "I love {$var}";

Above would return the following: I love my variable

ImportError: No module named tensorflow

with python2

pip show tensorflow to check install

python test.py to run test

with python3

pip3 show tensorflow to check install

python3 test.py to run test

test.py

import tensorflow as tf
import numpy as np

c = np.array([[3.,4], [5.,6], [6.,7]])
step = tf.reduce_mean(c, 1)                                                                                 
with tf.Session() as sess:
    print(sess.run(step))

Or, if you haven't install tensorflow yet, try the offical document

Node Multer unexpected field

The <NAME> you use in multer's upload.single(<NAME>) function must be the same as the one you use in <input type="file" name="<NAME>" ...>.

So you need to change

var type = upload.single('file')

to

var type = upload.single('recfile')

in you app.js

Hope this helps.

Python argparse command line flags without arguments

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag

Bootstrap 3: Text overlay on image

Is this what you're after?

http://jsfiddle.net/dCNXU/1/

I added :text-align:center to the div and image

How to use an environment variable inside a quoted string in Bash

Note that COLUMNS is:

  1. NOT an environment variable. It is an ordinary bash parameter that is set by bash itself.
  2. Set automatically upon receipt of a SIGWINCH signal.

That second point usually means that your COLUMNS variable will only be set in your interactive shell, not in a bash script.

If your script's stdin is connected to your terminal you can manually look up the width of your terminal by asking your terminal:

tput cols

And to use this in your SVN command:

svn diff "$@" --diff-cmd /usr/bin/diff -x "-y -w -p -W $(tput cols)"

(Note: you should quote "$@" and stay away from eval ;-))

How do you modify a CSS style in the code behind file for divs in ASP.NET?

Another way to do it:

testSpace.Style.Add("display", "none");

or

testSpace.Style["background-image"] = "url(images/foo.png)";

in vb.net you can do it this way:

testSpace.Style.Item("display") = "none"

Circle drawing with SVG's arc path

Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.

function(cx, cy, r, deg){
    var theta = deg*Math.PI/180,
        dx = r*Math.cos(theta),
        dy = -r*Math.sin(theta);
    return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}

Span inside anchor or anchor inside span or doesn't matter?

Semantically I think makes more sense as is a container for a single element and if you need to nest them then that suggests more than element will be inside of the outer one.

Regex match text between tags

/<b>(.*?)<\/b>/g

Regular expression visualization

Add g (global) flag after:

/<b>(.*?)<\/b>/g.exec(str)
             //^-----here it is 

However if you want to get all matched elements, then you need something like this:

var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";

var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
   return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"] 

If an element has attributes, regexp will be:

/<b [^>]+>(.*?)<\/b>/g.exec(str)

Blue and Purple Default links, how to remove?

By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-

For example color is: #000

a:visited, a:hover, a:focus {
    text-decoration: none;
    color: #000;
}

If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code

   a:hover {
        color: red;
    }
    a:visited {
        color: green;
    }
    a:focus {
        color: yellow;
    }

NB: good practice is to use color code.

Dynamically change bootstrap progress bar value when checkboxes checked

Bootstrap 4 progress bar

<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>

Javascript

change progress bar on next/previous page actions

var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);        
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');

c++ integer->std::string conversion. Simple function?

Now in c++11 we have

#include <string>
string s = std::to_string(123);

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

How to get the value of an input field using ReactJS?

In react 16, I use

<Input id="number" 
       type="time" 
       onChange={(evt) => { console.log(evt.target.value); }} />

Python pandas: fill a dataframe row by row

If your input rows are lists rather than dictionaries, then the following is a simple solution:

import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])

pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
#    A  B  C
# 0  1  2  3
# 1  4  5  6

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.

In my case the solution was as follows:

Script - stringify the original array (without using a named property)

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: mycontrolleraction,
        data: JSON.stringify(things)
    });

And in the controller method, use [FromBody]

    [HttpPost]
    public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
    {
        return Ok();
    }

Failures include:

  • Naming the content

    data: { content: nodes }, // Server error 500

  • Not having the contentType = Server error 500

Notes

  • dataType is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).
  • List<Thing> also works in the controller method

android: how to change layout on button click?

The logcat shows the error, you should call super.onCreate(savedInstanceState) :

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    //... your code
}

What is the difference between print and puts?

puts call the to_s of each argument and adds a new line to each string, if it does not end with new line. print just output each argument by calling their to_s.

for example: puts "one two": one two

{new line}

puts "one two\n": one two

{new line} #puts will not add a new line to the result, since the string ends with a new line

print "one two": one two

print "one two\n": one two

{new line}

And there is another way to output: p

For each object, directly writes obj.inspect followed by a newline to the program’s standard output.

It is helpful to output debugging message. p "aa\n\t": aa\n\t

How to get a path to the desktop for current user in C#?

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Do you get charged for a 'stopped' instance on EC2?

This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.

If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.

If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.

Most efficient way to create a zero filled JavaScript array?

_x000D_
_x000D_
const arr = Array.from({ length: 10 }).fill(0)
_x000D_
_x000D_
_x000D_

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

Using Keras & Tensorflow with AMD GPU

The original question on this post was: How to get Keras and Tensorflow to run with an AMD GPU.

The answer to this question is as followed:

1.) Keras will work if you can make Tensorflow work correctly (optionally within your virtual/conda environment).

2.) To get Tensorflow to work on an AMD GPU, as others have stated, one way this could work is to compile Tensorflow to use OpenCl. To do so read the link below. But for brevity I will summarize the required steps here:

  • You will need AMDs proprietary drivers. These are currently only available on Ubuntu 14.04 (the version before Ubuntu decided to change the way the UI is rendered). Support for Ubuntu 16.04 is at the writing of this post limited to a few GPUs through AMDProDrivers. Readers who want to do deep learning on AMD GPUs should be aware of this!

  • Compiling Tensorflow with OpenCl support also requires you to obtain and install the following prerequisites: OpenCl headers, ComputeCpp.

  • After the prerequisites are fulfilled, configure your build. Note that there are 3 options for compiling Tensorflow: Std Tensorflow (stable), Benoits Steiner's Tensorflow-opencl (developmental), and Luke Iwanski's Tensorflow-opencl (highly experimental) which you can pull from github. Also note that if you decide to build from any of the opencl versions, the question to use opencl will be missing because it is assumed that you are using it. Conversely, this means that if you configure from the standard tensorflow, you will need to select "Yes" when the configure script asks you to use opencl and "NO" for CUDA.

  • Then run tests like so:

    $ bazel test --config=sycl -k --test_timeout 1600 -- //tensorflow/... -//tensorflow/contrib/... -//tensorflow/java/... -//tensorflow /compiler/...

Update: Doing this on my setup takes exceedingly long on my setup. The part that takes long are all the tests running. I am not sure what this means but a lot of my tests are timeing out at 1600 seconds. The duration can probably be shortened at the expense of more tests timeing out. Alternatively, you can just build tensor flow without tests. At the time of this writing, running the tests has taken 2 days already.

Or just build the pip package like so:

bazel build --local_resources 2048,.5,1.0 -c opt --config=sycl //tensorflow/tools/pip_package:build_pip_package

Please actually read the blog post over at Codeplay: Lukas Iwansky posted a comprehensive tutorial post on how to get Tensorflow to work with OpenCl just on March 30th 2017. So this is a very recent post. There are also some details which I did not write about here.

As indicated in the many posts above, little bits of information are spread throughout the interwebs. What Lukas' post adds in terms of value is that all the information was put together into one place which should make setting up Tensforflow and OpenCl a bit less daunting. I will only provide a link here:

https://www.codeplay.com/portal/03-30-17-setting-up-tensorflow-with-opencl-using-sycl

A slightly more complete walk-through has been posted here:

http://deep-beta.co.uk/setting-up-tensorflow-with-opencl-using-sycl/

It differs mainly by explicitly telling the user that he/she needs to:

  • create symlinks to a subfolder
  • and then actually install tensorflow via "python setup.py develop" command.

Note an alternative approach was mentioned above using tensorflow-cl:

https://github.com/hughperkins/tensorflow-cl

I am unable to discern which approach is better at this time though it appears that this approach is less active. Fewer issues are posted, and fewer conversations to resolve those issues are happening. There was a major push last year. Additional pushes have ebbed off since November 2016 although Hugh seems to have pushed some updates a few days ago as of the writing of this post. (Update: If you read some of the documentation readme, this version of tensorflowo now only relies on community support as the main developer is busy with life.)

UPDATE (2017-04-25): I have some notes based on testing tensorflow-opencl below.

  • The future user of this package should note that using opencl means that all the heavy-lifting in terms of computing is shifted to the GPU. I mention this because I was personally thinking that the compute work-load would be shared between my CPU and iGPU. This means that the power of your GPU is very important (specifically, bandwidth, and available VRAM).

Following are some numbers for calculating 1 epoch using the CIFAR10 data set for MY SETUP (A10-7850 with iGPU). Your mileage will almost certainly vary!

  • Tensorflow (via pip install): ~ 1700 s/epoch
  • Tensorflow (w/ SSE + AVX): ~ 1100 s/epoch
  • Tensorflow (w/ opencl & iGPU): ~ 5800 s/epoch

You can see that in this particular case performance is worse. I attribute this to the following factors:

  • The iGPU only has 1GB. This leads to a lot of copying back and forth between CPU and GPU. (Opencl 1.2 does not have the ability to data pass via pointers yet; instead data has to be copied back and forth.)
  • The iGPU only has 512 stream processors (and 32 Gb/s memory bandwidth) which in this case is slower than 4 CPUs using SSE4 + AVX instruction sets.
  • The development of tensorflow-opencl is in it's beginning stages, and a lot of optimizations in SYCL etc. have not been done yet.

If you are using an AMD GPU with more VRAM and more stream processors, you are certain to get much better performance numbers. I would be interested to read what numbers people are achieving to know what's possible.

I will continue to maintain this answer if/when updates get pushed.

3.) An alternative way is currently being hinted at which is using AMD's RocM initiative, and miOpen (cuDNN equivalent) library. These are/will be open-source libraries that enable deep learning. The caveat is that RocM support currently only exists for Linux, and that miOpen has not been released to the wild yet, but Raja (AMD GPU head) has said in an AMA that using the above, it should be possible to do deep learning on AMD GPUs. In fact, support is planned for not only Tensorflow, but also Cafe2, Cafe, Torch7 and MxNet.

String to LocalDate

You may have to go from DateTime to LocalDate.

Using Joda Time:

DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MMM-dd");
DateTime dateTime = FORMATTER.parseDateTime("2005-nov-12");
LocalDate localDate = dateTime.toLocalDate();

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Effect of using sys.path.insert(0, path) and sys.path(append) when loading modules

I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :

1) insert and append methods are not specific to sys.path and as in other languages they add an item into a list or array and :
* append(item) add item to the end of the list,
* insert(n, item) inserts the item at the nth position in the list (0 at the beginning, 1 after the first element, etc ...).

2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
* If you have no file name collisions, the order of the path has no impact,
* If you look after a function already defined in the path and you use append to add your path, you will not get your function but the predefined one.

But I think that it is better to use append and not insert to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.

asp.net mvc @Html.CheckBoxFor

CheckBoxFor takes a bool, you're passing a List<CheckBoxes> to it. You'd need to do:

@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
    @Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
    @Html.HiddenFor(m => m.EmploymentType[i].Text)
    @Html.DisplayFor(m => m.EmploymentType[i].Text)
}

Notice I've added a HiddenFor for the Text property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.

Edit, as shown in your comments, your EmploymentType list is null when the view is served. You'll need to populate that too, by doing this in your action method:

public ActionResult YourActionMethod()
{
    CareerForm model = new CareerForm();

    model.EmploymentType = new List<CheckBox>
    {
        new CheckBox { Text = "Fulltime" },
        new CheckBox { Text = "Partly" },
        new CheckBox { Text = "Contract" }
    };

    return View(model);
}

Center text in table cell

How about simply (Please note, come up with a better name for the class name this is simply an example):

.centerText{
   text-align: center;
}


<div>
   <table style="width:100%">
   <tbody>
   <tr>
      <td class="centerText">Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td class="centerText">Cell 3</td>
      <td>Cell 4</td>
    </tr>
    </tbody>
    </table>
</div>

Example here

You can place the css in a separate file, which is recommended. In my example, I created a file called styles.css and placed my css rules in it. Then include it in the html document in the <head> section as follows:

<head>
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>

The alternative, not creating a seperate css file, not recommended at all... Create <style> block in your <head> in the html document. Then just place your rules there.

<head>
 <style type="text/css">
   .centerText{
       text-align: center;
    }
 </style>
</head>

Get the IP Address of local computer

In DEV C++, I used pure C with WIN32, with this given piece of code:

case IDC_IP:

             gethostname(szHostName, 255);
             host_entry=gethostbyname(szHostName);
             szLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
             //WSACleanup(); 
             writeInTextBox("\n");
             writeInTextBox("IP: "); 
             writeInTextBox(szLocalIP);
             break;

When I click the button 'show ip', it works. But on the second time, the program quits (without warning or error). When I do:

//WSACleanup(); 

The program does not quit, even clicking the same button multiple times with fastest speed. So WSACleanup() may not work well with Dev-C++..

MySQL config file location - redhat linux server

The information you want can be found by running

mysql --help

or

mysqld --help --verbose

I tried this :

    mysql --help | grep Default -A 1

And the output:

                      (Defaults to on; use --skip-auto-rehash to disable.)
  -A, --no-auto-rehash 
--
                      (Defaults to on; use --skip-line-numbers to disable.)
  -L, --skip-line-numbers 
--
                      (Defaults to on; use --skip-column-names to disable.)
  -N, --skip-column-names 
--
                      (Defaults to on; use --skip-reconnect to disable.)
  -s, --silent        Be more silent. Print results with a tab as separator,
--
  --default-auth=name Default authentication client-side plugin to use.
  --binary-mode       By default, ASCII '\0' is disallowed and '\r\n' is
--
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf 

how to convert string into dictionary in python 3.*?

  1. literal_eval, a somewhat safer version of eval (will only evaluate literals ie strings, lists etc):

    from ast import literal_eval
    
    python_dict = literal_eval("{'a': 1}")
    
  2. json.loads but it would require your string to use double quotes:

    import json
    
    python_dict = json.loads('{"a": 1}')
    

Xcode 10: A valid provisioning profile for this executable was not found

For our team, nothing helped. We have spend a couple of days and tried out every step that was mentioned here above in answers and comments. We tried with XCode 10 and even XCode 9.2 on an App, that is on the App store since many years.

The issue began after upgrading to MacOS Mojave. Unfortunately, going back to HighSierra didn't help then.

At least we was able again to ship into App store after we've created new certificate and provisioning profile. But we still are not able any more to test our App in release mode on real device, which is necessary to test InApp-purchases.

In short: Archiving and submission works well, running on real device not!

Several developers, several devices, macbooks, XCode versions....

At the end we had to change the AppID for being able again to test on real device.

Therefor we run two different projects now: one for shipping to TestFlight/AppStore with the real AppID and one for development purposes with another AppID.

Although this only happens on ONE particular App of our company and not all the others, we expect to run into similar issues in the future as things get more worse with Apple's development tools...

Unsigned values in C

Assign a int -1 to an unsigned: As -1 does not fit in the range [0...UINT_MAX], multiples of UINT_MAX+1 are added until the answer is in range. Evidently UINT_MAX is pow(2,32)-1 or 429496725 on OP's machine so a has the value of 4294967295.

    unsigned int a = -1;

The "%x", "%u" specifier expects a matching unsigned. Since these do not match, "If a conversion specification is invalid, the behavior is undefined. If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." C11 §7.21.6.1 9. The printf specifier does not change b.

    printf("%x\n", b);  // UB
    printf("%u\n", b);  // UB

The "%d" specifier expects a matching int. Since these do not match, more UB.

    printf("%d\n", a);  // UB

Given undefined behavior, the conclusions are not supported.


both cases, the bytes are the same (ffffffff).

Even with the same bit pattern, different types may have different values. ffffffff as an unsigned has the value of 4294967295. As an int, depending signed integer encoding, it has the value of -1, -2147483647 or TBD. As a float it may be a NAN.

what is unsigned word for?

unsigned stores a whole number in the range [0 ... UINT_MAX]. It never has a negative value. If code needs a non-negative number, use unsigned. If code needs a counting number that may be +, - or 0, use int.


Update: to avoid a compiler warning about assigning a signed int to unsigned, use the below. This is an unsigned 1u being negated - which is well defined as above. The effect is the same as a -1, but conveys to the compiler direct intentions.

unsigned int a = -1u;

How to properly create composite primary keys - MYSQL

I would not make the primary key of the "info" table a composite of the two values from other tables.

Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?

I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.

how to make UITextView height dynamic according to text length?

This answer may be late but I hope it helps someone.

For me, these 2 lines of code worked:

textView.isScrollEnabled = false
textView.sizeToFit()

But don't set height constraint for your Textview

Create a new file in git bash

If you are using the Git Bash shell, you can use the following trick:

> webpage.html

This is actually the same as:

echo "" > webpage.html

Then, you can use git add webpage.html to stage the file.

.bashrc at ssh login

For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:

TypeScript getting error TS2304: cannot find name ' require'

I've yet another answer that builds upon all previous ones that describe npm install @types/node and including node in tsconfig.json / compilerOptions / types.

In my case, I have a base tsConfig.json and a separate one in the Angular application that extends this one:

{
    "extends": "../../tsconfig.json",
    "compilerOptions": {
        "outDir": "../out-tsc/app",
        "types": []
 },

My problem was the empty types in this tsconfi.app.json - it clobbers the one in the base configuration.

'const string' vs. 'static readonly string' in C#

When you use a const string, the compiler embeds the string's value at compile-time.
Therefore, if you use a const value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.

A static readonly string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.

This also means that a static readonly string can use non-constant members, such as Environment.UserName or DateTime.Now.ToString(). A const string can only be initialized using other constants or literals.
Also, a static readonly string can be set in a static constructor; a const string can only be initialized inline.

Note that a static string can be modified; you should use static readonly instead.

Setting font on NSAttributedString on UITextView disregards line spacing

You can use this example and change it's implementation like this:

[self enumerateAttribute:NSParagraphStyleAttributeName
                 inRange:NSMakeRange(0, self.length)
                 options:0
              usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
                  NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];

                  //add your specific settings for paragraph
                  //...
                  //...

                  [self removeAttribute:NSParagraphStyleAttributeName range:range];
                  [self addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
              }];

Read a variable in bash with a default value

You can use parameter expansion, e.g.

read -p "Enter your name [Richard]: " name
name=${name:-Richard}
echo $name

Including the default value in the prompt between brackets is a fairly common convention

What does the :-Richard part do? From the bash manual:

${parameter:-word} If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

Also worth noting that...

In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

So if you use webpath=${webpath:-~/httpdocs} you will get a result of /home/user/expanded/path/httpdocs not ~/httpdocs, etc.

Why can't I have "public static const string S = "stuff"; in my Class?

From the C# language specification (PDF page 287 - or 300th page of the PDF):

Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier.

How do I fix 'ImportError: cannot import name IncompleteRead'?

I tried with every answer avobe, but couldn't make it.

Did this and worked

sudo apt-get purge python-virtualenv
sudo pip install pip -U

After that I just installed virtualenv with pip

sudo pip install virtualenv

I built the virtualenv that I was working on and the package was installed easily. Get into the virtualenv by using source /bin/activate and try to install your package, for example:

pip install terminado

It worked for me, although I was using python2.7 not python3