Programs & Examples On #Restart

Restart refers to the process where a software program or system is systematically (and preferably gracefully) shut down then automatically invoked to full functionality without intervention from the user.

Basic Apache commands for a local Windows machine

For frequent uses of this command I found it easy to add the location of C:\xampp\apache\bin to the PATH. Use whatever directory you have this installed in.

Then you can run from any directory in command line:

httpd -k restart

The answer above that suggests httpd -k -restart is actually a typo. You can see the commands by running httpd /?

How can I restart a Java application?

System.err.println("Someone is Restarting me...");
setVisible(false);
try {
    Thread.sleep(600);
} catch (InterruptedException e1) {
    e1.printStackTrace();
}
setVisible(true);

I guess you don't really want to stop the application, but to "Restart" it. For that, you could use this and add your "Reset" before the sleep and after the invisible window.

How to restart remote MySQL server running on Ubuntu linux?

Another way is:

systemctl restart mysql

How do I shutdown, restart, or log off Windows via a bat file?

Some additions to the shutdown and rundll32.exe shell32.dll,SHExitWindowsEx n commands.

LOGOFF - allows you to logoff user by sessionid or session name

PSShutdown - requires a download from windows sysinternals.

bootim.exe - windows 10/8 shutdown iu

change/chglogon - prevents new users to login or take another session

NET SESSION /DELETE - ends a session for user

wusa /forcerestart /quiet - windows update manager but also can restart the machine

tsdiscon - disconnects you

rdpinit - logs you out , though I cant find any documentation at the moment

Stop MySQL service windows

just type exit

and u are out of mysql in cmd in windows

Android Service Stops When App Is Closed

make you service like this in your Mainifest

 <service
            android:name=".sys.service.youservice"
            android:exported="true"
        android:process=":ServiceProcess" />

then your service will run on other process named ServiceProcess


if you want make your service never die :

  1. onStartCommand() return START_STICKY

  2. onDestroy() -> startself

  3. create a Deamon service

  4. jin -> create a Native Deamon process, you can find some open-source projects on github

  5. startForeground() , there is a way to startForeground without Notification ,google it

How to stop (and restart) the Rails Server?

In case that doesn't work there is another way that works especially well in Windows: Kill localhost:3000 process from Windows command line

Using Alert in Response.Write Function in ASP.NET

Concatenate the string separating the slash and the word script in this way.

Response.Write("<script language='javascript'>alert('Especifique Usuario y Contraseña');</" + "script>");

How to set up java logging using a properties file? (java.util.logging)

Logger log = Logger.getLogger("myApp");
log.setLevel(Level.ALL);
log.info("initializing - trying to load configuration file ...");

//Properties preferences = new Properties();
try {
    //FileInputStream configFile = new //FileInputStream("/path/to/app.properties");
    //preferences.load(configFile);
    InputStream configFile = myApp.class.getResourceAsStream("app.properties");
    LogManager.getLogManager().readConfiguration(configFile);
} catch (IOException ex)
{
    System.out.println("WARNING: Could not open configuration file");
    System.out.println("WARNING: Logging not configured (console output only)");
}
log.info("starting myApp");

this is working..:) you have to pass InputStream in readConfiguration().

Passing references to pointers in C++

Try:

void myfunc(string& val)
{
    // Do stuff to the string pointer
}

// sometime later 
{
    // ...
    string s;
    myfunc(s);
    // ...
}

or

void myfunc(string* val)
{
    // Do stuff to the string pointer
}

// sometime later 
{
    // ...
    string s;
    myfunc(&s);
    // ...
}

This declaration has no storage class or type specifier in C++

This is a mistake:

m.check(side);

That code has to go inside a function. Your class definition can only contain declarations and functions.

Classes don't "run", they provide a blueprint for how to make an object.

The line Message m; means that an Orderbook will contain Message called m, if you later create an Orderbook.

Access props inside quotes in React JSX

Instead of adding variables and strings, you can use the ES6 template strings! Here is an example:

<img className="image" src={`images/${this.props.image}`} />

As for all other JavaScript components inside JSX, use template strings inside of curly braces. To "inject" a variable use a dollar sign followed by curly braces containing the variable you would like to inject. For example:

{`string ${variable} another string`}

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

Copying text outside of Vim with set mouse=a enabled

Another OSX-Mac option is to uncheck View->Allow Mouse Reporting (or press ?-R to toggle it.) This allows you to toggle between mouse interaction and mouse selecting, which might be useful when selecting and copy/pasting a few bits because you don't have to hold a modifier key to do it.

Note for Multiline with line numbers:

I usually have line numbers enabled so this will also copy the line numbers if you select multiple lines. If you want to copy multiple lines without the line numbers disable the numbers with :set nonu and then you can :set nu to re-enable them after you're done copying.

How to run Pip commands from CMD

Little side note for anyone new to Python who didn't figure it out by theirself: this should be automatic when installing Python, but just in case, note that to run Python using the python command in Windows' CMD you must first add it to the PATH environment variable, as explained here.


To execute Pip, first of all make sure you have it installed, so type in your CMD:

> python
>>> import pip
>>>

And it should proceed with no error. Otherwise, if this fails, you can look here to see how to install it. Now that you are sure you've got Pip, you can run it from CMD with Python using the -m (module) parameter, like this:

> python -m pip <command> <args>

Where <command> is any Pip command you want to run, and <args> are its relative arguments, separated by spaces.

For example, to install a package:

> python -m pip install <package-name>

Eclipse: The resource is not on the build path of a Java project

You can add the src folder to build path by:

  1. Select Java perspective.
  2. Right click on src folder.
  3. Select Build Path > Use a source folder.

And you are done. Hope this help.

EDIT: Refer to the Eclipse documentation

JavaScript - Use variable in string match

You have to use RegExp object if your pattern is string

var xxx = "victoria";
var yyy = "i";
var rgxp = new RegExp(yyy, "g");
alert(xxx.match(rgxp).length);

If pattern is not dynamic string:

var xxx = "victoria";
var yyy = /i/g;
alert(xxx.match(yyy).length);

Where's javax.servlet?

Have you instaled the J2EE? If you installed just de standard (J2SE) it won´t find.

Modify table: How to change 'Allow Nulls' attribute from not null to allow null

So the simplest way is,

alter table table_name change column_name column_name int(11) NULL;

How to really read text file from classpath in Java

This is how I read all lines of a text file on my classpath, using Java 7 NIO:

...
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;

...

Files.readAllLines(
    Paths.get(this.getClass().getResource("res.txt").toURI()), Charset.defaultCharset());

NB this is an example of how it can be done. You'll have to make improvements as necessary. This example will only work if the file is actually present on your classpath, otherwise a NullPointerException will be thrown when getResource() returns null and .toURI() is invoked on it.

Also, since Java 7, one convenient way of specifying character sets is to use the constants defined in java.nio.charset.StandardCharsets (these are, according to their javadocs, "guaranteed to be available on every implementation of the Java platform.").

Hence, if you know the encoding of the file to be UTF-8, then specify explicitly the charset StandardCharsets.UTF_8

Android ImageView Fixing Image Size

Fix ImageView's size with dp or fill_parent and set android:scaleType to fitXY.

Using Node.JS, how do I read a JSON file into (server) memory?

If you are looking for a complete solution for Async loading a JSON file from Relative Path with Error Handling

  // Global variables
  // Request path module for relative path
    const path = require('path')
  // Request File System Module
   var fs = require('fs');


// GET request for the /list_user page.
router.get('/listUsers', function (req, res) {
   console.log("Got a GET request for list of users");

     // Create a relative path URL
    let reqPath = path.join(__dirname, '../mock/users.json');

    //Read JSON from relative path of this file
    fs.readFile(reqPath , 'utf8', function (err, data) {
        //Handle Error
       if(!err) {
         //Handle Success
          console.log("Success"+data);
         // Parse Data to JSON OR
          var jsonObj = JSON.parse(data)
         //Send back as Response
          res.end( data );
        }else {
           //Handle Error
           res.end("Error: "+err )
        }
   });
})

Directory Structure:

enter image description here

Can I open a dropdownlist using jQuery

I've come across the same problem and I have a solution. A function called ExpandSelect() that emulates mouse clicking on "select" element, it does so by creating an another <select> element that is absolutely posioned and have multiple options visible at once by setting the size attribute. Tested in all major browsers: Chrome, Opera, Firefox, Internet Explorer. Explanation of how it works, along with the code here:

Edit (link was broken).

I've created a project at Google Code, go for the code there:

http://code.google.com/p/expandselect/

Screenshots

There is a little difference in GUI when emulating click, but it does not really matter, see it for yourself:

When mouse clicking:

MouseClicking
(source: googlecode.com)

When emulating click:

EmulatingClicking
(source: googlecode.com)

More screenshots on project's website, link above.

SQL Server CTE and recursion example

I haven't tested your code, just tried to help you understand how it operates in comment;

WITH
  cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
  AS
  (
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
    SELECT EmployeeID, FirstName, LastName, ManagerID, 1
    FROM Employees
    WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
    UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>    
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
    SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
      r.EmpLevel + 1
    FROM Employees e
      INNER JOIN cteReports r
        ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
  )
SELECT
  FirstName + ' ' + LastName AS FullName,
  EmpLevel,
  (SELECT FirstName + ' ' + LastName FROM Employees
    WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID

The simplest example of a recursive CTE I can think of to illustrate its operation is;

;WITH Numbers AS
(
    SELECT n = 1
    UNION ALL
    SELECT n + 1
    FROM Numbers
    WHERE n+1 <= 10
)
SELECT n
FROM Numbers

Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.

A1: In this case, N is not a variable. N is an alias. It is the equivalent of SELECT 1 AS N. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE in T-SQL. I've included the analog of a simple CTE in Excel to try and illustrate in a more familiar way what is happening.

--  Outside
;WITH CTE (MyColName) AS
(
    SELECT 1
)
-- Inside
;WITH CTE AS
(
    SELECT 1 AS MyColName
    -- Or
    SELECT MyColName = 1  
    -- Etc...
)

Excel_CTE

Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager

A2:

Does this code answer your question?

--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS 
(
    SELECT 1,      'Keith',      NULL   UNION ALL
    SELECT 2,      'Josh',       1      UNION ALL
    SELECT 3,      'Robin',      1      UNION ALL
    SELECT 4,      'Raja',       2      UNION ALL
    SELECT 5,      'Tridip',     NULL   UNION ALL
    SELECT 6,      'Arijit',     5      UNION ALL
    SELECT 7,      'Amit',       5      UNION ALL
    SELECT 8,      'Dev',        6   
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
    --  Anchor
    SELECT   ID
            ,Name
            ,MgrID
            ,nLevel = 1
            ,Family = ROW_NUMBER() OVER (ORDER BY Name)
    FROM Employee
    WHERE MgrID IS NULL

    UNION ALL
    --  Recursive query
    SELECT   E.ID
            ,E.Name
            ,E.MgrID
            ,H.nLevel+1
            ,Family
    FROM Employee   E
    JOIN Hierarchy  H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel

Another one sql with tree structure

SELECT ID,space(nLevel+
                    (CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
                )+Name
FROM Hierarchy
ORDER BY Family, nLevel

How to cancel a pull request on github?

Super EASY way to close a Pull Request - LATEST!

  1. Navigate to the Original Repository where the pull request has been submitted to.
  2. Select the Pull requests tab
  3. Select your pull request that you wish to remove. This will open it up.
  4. Towards the bottom, just enter a valid comment for closure and press Close Pull Request button

enter image description here

How to force 'cp' to overwrite directory instead of creating another one inside?

The operation you defined is a "merge" and you cannot do that with cp. However, if you are not looking for merging and ok to lose the folder bar then you can simply rm -rf bar to delete the folder and then mv foo bar to rename it. This will not take any time as both operations are done by file pointers, not file contents.

How can I remove the last character of a string in python?

You could use String.rstrip.

result = string.rstrip('/')

Can we locate a user via user's phone number in Android?

Yess, possible with conditions:

If you have your app installed in the user phone and a server app communicating with this app, and there at last one of location service providers activated in the user phone, and some horrible android permissions!

In most of android phones there 3 location providers that can give exact location (GPS_PROVIDER 1m) or estimated (NETWORK_PROVIDER around 2-20m) and PASSIVE_PROVIDER (more in LocationManager official documentation).

1* App sends SMS to user's phone

Yess, can be server app or you create an android app if you want something automated, so you can do it manually by sending SMS from your default SMS app! I use Kannel: Open Source WAP and SMS Gateway and here (lot of APIs to send SMS )

2* App receives SMS at user's phone from the SMS sender

Yess, you can get all received SMS, and you can filter them by sender phone number! and do some actions when your specified sms received, basic tuto here (i do some actions according to the content of my SMS)

3* App gets location coordinates of the user's phone

Yess, you can get actual user coordinates easily if one of location providers is activated, so you can get last known location when the user have activated one of location providers, if those disabled or the phone don't have GPS hardware you can use Open Cell Id api to get the nearest cell coordinates(10m-10Km) or Loc8 api but those not available in all around the world, and some apps use IP location apis to get the country, city and province, here the simplest way to get current user location.

4* App sends location coordinates to the SMS sender via SMS

Yess, you can get sender phone number and send user location, immediately when SMS received or at specified times in the day.

(Those 4 yesses for you :) )

Viber and other apps that access to users locations, identify there users by there phone numbers by obligating them to send SMS to the server app to create an account and activate the free service (Ex:VOIP) , and lunch a service that can:

  • Listen for location changes (GPS, Network or Cell Id)
  • Send user location periodically(Ex: each 2 hours) or when user position changed!
  • Stock user locations in file and create a map based on daily locations
  • Receive SMS and update user location
  • Receive server app commend and update user location
  • Send events when user go inside or outside of a defined circle
  • Listen for what user say and record it or open live voip call :s
  • Maybe anything you think or u want to do :) !

And your application users must accept all of that when installing it, of corse i don't gonna install apps like this because i read permissions before installing :) and permissions maybe something like that:

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />    
<uses-permission android:name="android.permission.INTERNET" />
<-- and more if you wanna more -->

The final user will accept for something like that (those permissions of an android app u asked about):

This app has access to these permissions:

Your accounts -create accounts and set passwords -find accounts on the device -add or remove accounts -use accounts on the device -read Google service configuration

Your location -approximate location (network-based) -precise location (GPS and network-based)

Your messages -receive text messages (SMS) -send SMS messages -edit your text messages (SMS or MMS) -read your text messages (SMS or MMS)

Network communication -receive data from Internet -full network access -view Wi-Fi connections -view network connections -change network connectivity

Phone calls -read phone status and identity -directly call phone numbers

Storage -modify or delete the contents of your USB storage

Your applications information -retrieve running apps -close other apps -run at startup

Bluetooth -pair with Bluetooth devices -access Bluetooth settings

Camera -take pictures and videos

Other Application UI -draw over other apps

Microphone -record audio

Lock screen -disable your screen lock

Your social information -read your contacts -modify your contacts -read call log -write call log -read your social stream -write to your social stream

Development tools -read sensitive log data

System tools -modify system settings -send sticky broadcast -test access to protected storage

Affects battery -control vibration -prevent device from sleeping

Audio settings -change your audio settings

Sync Settings -read sync settings -toggle sync on and off -read sync statistics

Wallpaper -set wallpaper

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

This answer is a follow up to DaRKoN_'s answer that utilized the object filter:

[ObjectFilter(Param = "postdata", RootType = typeof(ObjectToSerializeTo))]
    public JsonResult ControllerMethod(ObjectToSerializeTo postdata) { ... }

I was having a problem figuring out how to send multiple parameters to an action method and have one of them be the json object and the other be a plain string. I'm new to MVC and I had just forgotten that I already solved this problem with non-ajaxed views.

What I would do if I needed, say, two different objects on a view. I would create a ViewModel class. So say I needed the person object and the address object, I would do the following:

public class SomeViewModel()
{
     public Person Person { get; set; }
     public Address Address { get; set; }
}

Then I would bind the view to SomeViewModel. You can do the same thing with JSON.

[ObjectFilter(Param = "jsonViewModel", RootType = typeof(JsonViewModel))] // Don't forget to add the object filter class in DaRKoN_'s answer.
public JsonResult doJsonStuff(JsonViewModel jsonViewModel)
{
     Person p = jsonViewModel.Person;
     Address a = jsonViewModel.Address;
     // Do stuff
     jsonViewModel.Person = p;
     jsonViewModel.Address = a;
     return Json(jsonViewModel);
}

Then in the view you can use a simple call with JQuery like this:

var json = { 
    Person: { Name: "John Doe", Sex: "Male", Age: 23 }, 
    Address: { Street: "123 fk st.", City: "Redmond", State: "Washington" }
};

$.ajax({
     url: 'home/doJsonStuff',
     type: 'POST',
     contentType: 'application/json',
     dataType: 'json',
     data: JSON.stringify(json), //You'll need to reference json2.js
     success: function (response)
     {
          var person = response.Person;
          var address = response.Address;
     }
});

Checking if a field contains a string

This should do the work

db.users.find({ username: { $in: [ /son/i ] } });

The i is just there to prevent restrictions of matching single cases of letters.

You can check the $regex documentation on MongoDB documentation. Here's a link: https://docs.mongodb.com/manual/reference/operator/query/regex/

Removing padding gutter from grid columns in Bootstrap 4

You can use the mixin make-col-ready and set the gutter width to zero:

@include make-col-ready(0);

How can I change my Cygwin home folder after installation?

I'd like to add a correction/update to the bit about $HOME taking precedence. The home directory in /etc/passwd takes precedence over everything.

I'm a long time Cygwin user and I just did a clean install of Windows 7 x64 and Cygwin V1.126. I was going nuts trying to figure out why every time I ran ssh I kept getting:

e:\>ssh foo.bar.com
Could not create directory '/home/dhaynes/.ssh'.
The authenticity of host 'foo.bar.com (10.66.19.19)' can't be established.
...

I add the HOME=c:\users\dhaynes definition in the Windows environment but still it kept trying to create '/home/dhaynes'. I tried every combo I could including setting HOME to /cygdrive/c/users/dhaynes. Googled for the error message, could not find anything, couldn't find anything on the cygwin site. I use cygwin from cmd.exe, not bash.exe but the problem was present in both.

I finally realized that the home directory in /etc/passwd was taking precedence over the $HOME environment variable. I simple re-ran 'mkpasswd -l >/etc/passwd' and that updated the home directory, now all is well with ssh.

That may be obvious to linux types with sysadmin experience but for those of us who primarily use Windows it's a bit obscure.

How to change the remote a branch is tracking?

I've found @critikaster's post helpful, except that I had to perform these commands with GIT 2.21:

$ git remote set-url origin https://some_url/some_repo
$ git push --set-upstream origin master

Correct way to work with vector of arrays

Use:

vector<vector<float>> vecArray; //both dimensions are open!

How do I find the install time and date of Windows?

You can simply check the creation date of Windows Folder (right click on it and check properties) :)

Cheap way to search a large text file for a string

This is entirely inspired by laurasia's answer above, but it refines the structure.

It also adds some checks:

  • It will correctly return 0 when searching an empty file for the empty string. In laurasia's answer, this is an edge case that will return -1.
  • It also pre-checks whether the goal string is larger than the buffer size, and raises an error if this is the case.

In practice, the goal string should be much smaller than the buffer for efficiency, and there are more efficient methods of searching if the size of the goal string is very close to the size of the buffer.

def fnd(fname, goal, start=0, bsize=4096):
    if bsize < len(goal):
        raise ValueError("The buffer size must be larger than the string being searched for.")
    with open(fname, 'rb') as f:
        if start > 0:
            f.seek(start)
        overlap = len(goal) - 1
        while True:
            buffer = f.read(bsize)
            pos = buffer.find(goal)
            if pos >= 0:
                return f.tell() - len(buffer) + pos
            if not buffer:
                return -1
            f.seek(f.tell() - overlap)

Using ALTER to drop a column if it exists in MySQL

I realise this thread is quite old now, but I was having the same problem. This was my very basic solution using the MySQL Workbench, but it worked fine...

  1. get a new sql editor and execute SHOW TABLES to get a list of your tables
  2. select all of the rows, and choose copy to clipboard (unquoted) from the context menu
  3. paste the list of names into another editor tab
  4. write your query, ie ALTER TABLE x DROP a;
  5. do some copying and pasting, so you end up with separate query for each table
  6. Toggle whether the workbench should stop when an error occurs
  7. Hit execute and look through the output log

any tables which had the table now haven't any tables which didn't will have shown an error in the logs

then you can find/replace 'drop a' change it to 'ADD COLUMN b INT NULL' etc and run the whole thing again....

a bit clunky, but at last you get the end result and you can control/monitor the whole process and remember to save you sql scripts in case you need them again.

Why shouldn't I use "Hungarian Notation"?

I cannot find a link but I remember reading somewhere (which I agree with) that avoiding Hungarian notation results in better programming style.

When you program a statement of your program, you should not be thinking about "what type this object is" before calling its method, but rather you should think "what do I want to do with it", "which message to send to it".

Kind of vague concept to explain, but I think it works.

For example, if you have customer name stored in variable customerName, you should not care if it is a string or some other class. More important to think what do you want from this object. Do you want it to print(), getFirstName(), getLastName(), convertToString() etc. Once you make it an instance of String class and take it as granted, you limit yourself and your design since you have to build up all other logic you need elsewhere in the code.

Best HTML5 markup for sidebar

Based on this HTML5 Doctor diagram, I'm thinking this may be the best markup:

<aside class="sidebar">
    <article id="widget_1" class="widget">...</article>
    <article id="widget_2" class="widget">...</article>
    <article id="widget_3" class="widget">...</article>
</aside> <!-- end .sidebar -->

I think it's clear that <aside> is the appropriate element as long as it's outside the main <article> element.

Now, I'm thinking that <article> is also appropriate for each widget in the aside. In the words of the W3C:

The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

FAQ

Questions from the top of my head since that time I gone crazy with jacoco.

My application server (jBoss, Glassfish..) located in Iraq, Syria, whatever.. Is it possible to get multi-module coverage when running integration tests on it? Jenkins and Sonar are also on different servers.

Yes. You have to use jacoco agent that runs in mode output=tcpserver, jacoco ant lib. Basically two jars. This will give you 99% success.

How does jacoco agent works?

You append a string

-javaagent:[your_path]/jacocoagent.jar=destfile=/jacoco.exec,output=tcpserver,address=*

to your application server JAVA_OPTS and restart it. In this string only [your_path] have to be replaced with the path to jacocoagent.jar, stored(store it!) on your VM where app server runs. Since that time you start app server, all applications that are deployed will be dynamically monitored and their activity (meaning code usage) will be ready for you to get in jacocos .exec format by tcl request.

Could I reset jacoco agent to start collecting execution data only since the time my test start?

Yes, for that purpose you need jacocoant.jar and ant build script located in your jenkins workspace.

So basically what I need from http://www.eclemma.org/jacoco/ is jacocoant.jar located in my jenkins workspace, and jacocoagent.jar located on my app server VM?

That's right.

I don't want to use ant, I've heard that jacoco maven plugin can do all the things too.

That's not right, jacoco maven plugin can collect unit test data and some integration tests data(see Arquillian Jacoco), but if you have for example rest assured tests as a separated build in jenkins, and want to show multi-module coverage, I can't see how maven plugin can help you.

What exactly does jacoco agent produce?

Only coverage data in .exec format. Sonar then can read it.

Does jacoco need to know where my java classes located are?

No, sonar does, but not jacoco. When you do mvn sonar:sonar path to classes comes into play.

So what about the ant script?

It has to be presented in your jenkins workspace. Mine ant script, I called it jacoco.xml looks like that:

<project name="Jacoco library to collect code coverage remotely" xmlns:jacoco="antlib:org.jacoco.ant">
    <property name="jacoco.port" value="6300"/>
    <property name="jacocoReportFile" location="${workspace}/it-jacoco.exec"/>

    <taskdef uri="antlib:org.jacoco.ant" resource="org/jacoco/ant/antlib.xml">
        <classpath path="${workspace}/tools/jacoco/jacocoant.jar"/>
    </taskdef>

    <target name="jacocoReport">
            <jacoco:dump address="${jacoco.host}" port="${jacoco.port}" dump="true" reset="true" destfile="${jacocoReportFile}" append="false"/>
    </target>

    <target name="jacocoReset">
            <jacoco:dump address="${jacoco.host}" port="${jacoco.port}" reset="true" destfile="${jacocoReportFile}" append="false"/>
        <delete file="${jacocoReportFile}"/>
    </target>
</project>

Two mandatory params you should pass when invoking this script -Dworkspace=$WORKSPACE use it to point to your jenkins workspace and -Djacoco.host=yourappserver.com host without http://

Also notice that I put my jacocoant.jar to ${workspace}/tools/jacoco/jacocoant.jar

What should I do next?

Did you start your app server with jacocoagent.jar?

Did you put ant script and jacocoant.jar in your jenkins workspace?

If yes the last step is to configure a jenkins build. Here is the strategy:

  1. Invoke ant target jacocoReset to reset all previously collected data.
  2. Run your tests
  3. Invoke ant target jacocoReport to get report

If everything is right, you will see it-jacoco.exec in your build workspace.

Look at the screenshot, I also have ant installed in my workspace in $WORKSPACE/tools/ant dir, but you can use one that is installed in your jenkins.

enter image description here

How to push this report in sonar?

Maven sonar:sonar will do the job (don't forget to configure it), point it to main pom.xml so it will run through all modules. Use sonar.jacoco.itReportPath=$WORKSPACE/it-jacoco.exec parameter to tell sonar where your integration test report is located. Every time it will analyse new module classes, it will look for information about coverage in it-jacoco.exec.

I already have jacoco.exec in my `target` dir, `mvn sonar:sonar` ignores/removes it

By default mvn sonar:sonar does clean and deletes your target dir, use sonar.dynamicAnalysis=reuseReports to avoid it.

Makefile ifeq logical or

As found on the mailing list archive,

one can use the filter function.

For example

ifeq ($(GCC_MINOR),$(filter $(GCC_MINOR),4 5))

filter X, A B will return those of A,B that are equal to X. Note, while this is not relevant in the above example, this is a XOR operation. I.e. if you instead have something like:

ifeq (4, $(filter 4, $(VAR1) $(VAR2)))

And then do e.g. make VAR1=4 VAR2=4, the filter will return 4 4, which is not equal to 4.

A variation that performs an OR operation instead is:

ifneq (,$(filter $(GCC_MINOR),4 5))

where a negative comparison against an empty string is used instead (filter will return en empty string if GCC_MINOR doesn't match the arguments). Using the VAR1/VAR2 example it would look like this:

ifneq (, $(filter 4, $(VAR1) $(VAR2)))

The downside to those methods is that you have to be sure that these arguments will always be single words. For example, if VAR1 is 4 foo, the filter result is still 4, and the ifneq expression is still true. If VAR1 is 4 5, the filter result is 4 5 and the ifneq expression is true.

One easy alternative is to just put the same operation in both the ifeq and else ifeq branch, e.g. like this:

ifeq ($(GCC_MINOR),4)
    @echo Supported version
else ifeq ($(GCC_MINOR),5)
    @echo Supported version
else
    @echo Unsupported version
endif

importing pyspark in python shell

export PYSPARK_PYTHON=/home/user/anaconda3/bin/python
export PYSPARK_DRIVER_PYTHON=jupyter
export PYSPARK_DRIVER_PYTHON_OPTS='notebook'

This is what I did for using my Anaconda distribution with Spark. This is Spark version independent. You can change the first line to your users' python bin. Also, as of Spark 2.2.0 PySpark is available as a Stand-alone package on PyPi but I am yet to test it out.

Show and hide divs at a specific time interval using jQuery

See InnerFade.

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

    function() {
        $('#portfolio').innerfade({
            speed: 'slow',
            timeout: 10000,
            type: 'sequence',
            containerheight: '220px'
        });
    });
</script>
<ul id="portfolio">
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kreation/good_guy__bad_guy.html">
        <img src="images/ggbg.gif" alt="Good Guy bad Guy" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kreation/whizzkids.html">
        <img src="images/whizzkids.gif" alt="Whizzkids" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/printdesign/koenigin_mutter.html">
        <img src="images/km.jpg" alt="Königin Mutter" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/webdesign/rt_reprotechnik_-_hybride_archivierung.html">
        <img src="images/rt_arch.jpg" alt="RT Hybride Archivierung" />
        </a>
    </li>
    <li>
        <a href="http://medienfreunde.com/deutsch/referenzen/kommunikation/tuev_sued_gruppe.html">
        <img src="images/tuev.jpg" alt="TÜV SÜD Gruppe" />
        </a>
    </li>
</ul>

How to use new PasswordEncoder from Spring Security

If you haven't actually registered any users with your existing format then you would be best to switch to using the BCrypt password encoder instead.

It's a lot less hassle, as you don't have to worry about salt at all - the details are completely encapsulated within the encoder. Using BCrypt is stronger than using a plain hash algorithm and it's also a standard which is compatible with applications using other languages.

There's really no reason to choose any of the other options for a new application.

Add a "sort" to a =QUERY statement in Google Spreadsheets

Sorting by C and D needs to be put into number form for the corresponding column, ie 3 and 4, respectively. Eg Order By 2 asc")

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

How can I join on a stored procedure?

The short answer is "you can't". What you'll need to do is either use a subquery or you could convert your existing stored procedure in to a table function. Creating it as function would depend on how "reusable" you would need it to be.

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

javascript popup alert on link click

You can use the onclick attribute, just return false if you don't want continue;

<script type="text/javascript">
function confirm_alert(node) {
    return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>

How to count the occurrence of certain item in an ndarray?

This can be done easily in the following method

y = np.array([0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1])
y.tolist().count(1)

How to call a C# function from JavaScript?

You can't. Javascript runs client side, C# runs server side.

In fact, your server will run all the C# code, generating Javascript. The Javascript then, is run in the browser. As said in the comments, the compiler doesn't know Javascript.

To call the functionality on your server, you'll have to use techniques such as AJAX, as said in the other answers.

How to make the first option of <select> selected with jQuery

Use:

$("#selectbox option:first").val()

Please find the working simple in this JSFiddle.

Setting ANDROID_HOME enviromental variable on Mac OS X

To set ANDROID_HOME, variable, you need to know how you installed android dev setup.

If you don't know you can check if the following paths exist in your machine. Add the following to .bashrc, .zshrc, or .profile depending on what you use

If you installed with homebrew,

export ANDROID_HOME=/usr/local/opt/android-sdk

Check if this path exists:

If you installed android studio following the website,

export ANDROID_HOME=~/Library/Android/sdk

Finally add it to path:

export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

If you're too lazy to open an editor do this:

echo "export ANDROID_HOME=~/Library/Android/sdk" >> ~/.bashrc
echo "export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools" >> ~/.bashrc

Codeigniter unset session

I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session.

session_unset();
session_destroy();

How can I style an Android Switch?

Alternative and much easier way is to use shapes instead of 9-patches. It is already explained here: https://stackoverflow.com/a/24725831/512011

How to stop event bubbling on checkbox click

Here's a trick that worked for me:

handleClick = e => {
    if (e.target === e.currentTarget) {
        // do something
    } else {
        // do something else
    }
}

Explanation: I attached handleClick to a backdrop of a modal window, but it also fired on every click inside of a modal window (because it was IN the backdrop div). So I added the condition (e.target === e.currentTarget), which is only fulfilled when a backdrop is clicked.

How to fix the "508 Resource Limit is reached" error in WordPress?

Actually it happens when the number of processes exceeds the limits set by the hosting provider.

To avoid either we need to enhance the capacity by hosting providers or we need to check in the code whether any process takes longer time (like background tasks).

Add characters to a string in Javascript

To use String.concat, you need to replace your existing text, since the function does not act by reference.

var text ="";
for (var member in list) {
        text = text.concat(list[member]);
}

Of course, the join() or += suggestions offered by others will work fine as well.

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

What's the key difference between HTML 4 and HTML 5?

Now W3c provides an official difference on their site:

http://www.w3.org/TR/html5-diff/

How large should my recv buffer be when calling recv in the socket library

For streaming protocols such as TCP, you can pretty much set your buffer to any size. That said, common values that are powers of 2 such as 4096 or 8192 are recommended.

If there is more data then what your buffer, it will simply be saved in the kernel for your next call to recv.

Yes, you can keep growing your buffer. You can do a recv into the middle of the buffer starting at offset idx, you would do:

recv(socket, recv_buffer + idx, recv_buffer_size - idx, 0);

Find out who is locking a file on a network share

Partial answer: With Process Explorer, you can view handles on a network share opened from your machine.

Use the Menu "Find Handle" and then you can type a path like this

\Device\LanmanRedirector\server\share\

How To Format A Block of Code Within a Presentation?

I've also thought of this. Finally, my solution is to use github gist. Don't forget it also has highlight functionality. Just copy it. :)

Auto margins don't center image in page

In my case the problem was that I had set min and max width without width itself.

copying all contents of folder to another folder using batch file?

Here's a solution with robocopy which copies the content of Folder1 into Folder2 going trough all subdirectories and automatically overwriting the files with the same name:

robocopy C:\Folder1 C:\Folder2 /COPYALL /E /IS /IT

Here:

/COPYALL copies all file information
/E copies subdirectories including empty directories
/IS includes the same files
/IT includes modified files with the same name

For more parameters see the official documentation: https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy

Note: it can be necessary to run the command as administrator, because of the argument /COPYALL. If you can't: just get rid of it.

Pass props to parent component in React.js

Edit: see the end examples for ES6 updated examples.

This answer simply handle the case of direct parent-child relationship. When parent and child have potentially a lot of intermediaries, check this answer.

Other solutions are missing the point

While they still work fine, other answers are missing something very important.

Is there not a simple way to pass a child's props to its parent using events, in React.js?

The parent already has that child prop!: if the child has a prop, then it is because its parent provided that prop to the child! Why do you want the child to pass back the prop to the parent, while the parent obviously already has that prop?

Better implementation

Child: it really does not have to be more complicated than that.

var Child = React.createClass({
  render: function () {
    return <button onClick={this.props.onClick}>{this.props.text}</button>;
  },
});

Parent with single child: using the value it passes to the child

var Parent = React.createClass({
  getInitialState: function() {
     return {childText: "Click me! (parent prop)"};
  },
  render: function () {
    return (
      <Child onClick={this.handleChildClick} text={this.state.childText}/>
    );
  },
  handleChildClick: function(event) {
     // You can access the prop you pass to the children 
     // because you already have it! 
     // Here you have it in state but it could also be
     //  in props, coming from another parent.
     alert("The Child button text is: " + this.state.childText);
     // You can also access the target of the click here 
     // if you want to do some magic stuff
     alert("The Child HTML is: " + event.target.outerHTML);
  }
});

JsFiddle

Parent with list of children: you still have everything you need on the parent and don't need to make the child more complicated.

var Parent = React.createClass({
  getInitialState: function() {
     return {childrenData: [
         {childText: "Click me 1!", childNumber: 1},
         {childText: "Click me 2!", childNumber: 2}
     ]};
  },
  render: function () {
    var children = this.state.childrenData.map(function(childData,childIndex) {
        return <Child onClick={this.handleChildClick.bind(null,childData)} text={childData.childText}/>;
    }.bind(this));
    return <div>{children}</div>;
  },

  handleChildClick: function(childData,event) {
     alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
     alert("The Child HTML is: " + event.target.outerHTML);
  }
});

JsFiddle

It is also possible to use this.handleChildClick.bind(null,childIndex) and then use this.state.childrenData[childIndex]

Note we are binding with a null context because otherwise React issues a warning related to its autobinding system. Using null means you don't want to change the function context. See also.

About encapsulation and coupling in other answers

This is for me a bad idea in term of coupling and encapsulation:

var Parent = React.createClass({
  handleClick: function(childComponent) {
     // using childComponent.props
     // using childComponent.refs.button
     // or anything else using childComponent
  },
  render: function() {
    <Child onClick={this.handleClick} />
  }
});

Using props: As I explained above, you already have the props in the parent so it's useless to pass the whole child component to access props.

Using refs: You already have the click target in the event, and in most case this is enough. Additionnally, you could have used a ref directly on the child:

<Child ref="theChild" .../>

And access the DOM node in the parent with

React.findDOMNode(this.refs.theChild)

For more advanced cases where you want to access multiple refs of the child in the parent, the child could pass all the dom nodes directly in the callback.

The component has an interface (props) and the parent should not assume anything about the inner working of the child, including its inner DOM structure or which DOM nodes it declares refs for. A parent using a ref of a child means that you tightly couple the 2 components.

To illustrate the issue, I'll take this quote about the Shadow DOM, that is used inside browsers to render things like sliders, scrollbars, video players...:

They created a boundary between what you, the Web developer can reach and what’s considered implementation details, thus inaccessible to you. The browser however, can traipse across this boundary at will. With this boundary in place, they were able to build all HTML elements using the same good-old Web technologies, out of the divs and spans just like you would.

The problem is that if you let the child implementation details leak into the parent, you make it very hard to refactor the child without affecting the parent. This means as a library author (or as a browser editor with Shadow DOM) this is very dangerous because you let the client access too much, making it very hard to upgrade code without breaking retrocompatibility.

If Chrome had implemented its scrollbar letting the client access the inner dom nodes of that scrollbar, this means that the client may have the possibility to simply break that scrollbar, and that apps would break more easily when Chrome perform its auto-update after refactoring the scrollbar... Instead, they only give access to some safe things like customizing some parts of the scrollbar with CSS.

About using anything else

Passing the whole component in the callback is dangerous and may lead novice developers to do very weird things like calling childComponent.setState(...) or childComponent.forceUpdate(), or assigning it new variables, inside the parent, making the whole app much harder to reason about.


Edit: ES6 examples

As many people now use ES6, here are the same examples for ES6 syntax

The child can be very simple:

const Child = ({
  onClick, 
  text
}) => (
  <button onClick={onClick}>
    {text}
  </button>
)

The parent can be either a class (and it can eventually manage the state itself, but I'm passing it as props here:

class Parent1 extends React.Component {
  handleChildClick(childData,event) {
     alert("The Child button data is: " + childData.childText + " - " + childData.childNumber);
     alert("The Child HTML is: " + event.target.outerHTML);
  }
  render() {
    return (
      <div>
        {this.props.childrenData.map(child => (
          <Child
            key={child.childNumber}
            text={child.childText} 
            onClick={e => this.handleChildClick(child,e)}
          />
        ))}
      </div>
    );
  }
}

But it can also be simplified if it does not need to manage state:

const Parent2 = ({childrenData}) => (
  <div>
     {childrenData.map(child => (
       <Child
         key={child.childNumber}
         text={child.childText} 
         onClick={e => {
            alert("The Child button data is: " + child.childText + " - " + child.childNumber);
                    alert("The Child HTML is: " + e.target.outerHTML);
         }}
       />
     ))}
  </div>
)

JsFiddle


PERF WARNING (apply to ES5/ES6): if you are using PureComponent or shouldComponentUpdate, the above implementations will not be optimized by default because using onClick={e => doSomething()}, or binding directly during the render phase, because it will create a new function everytime the parent renders. If this is a perf bottleneck in your app, you can pass the data to the children, and reinject it inside "stable" callback (set on the parent class, and binded to this in class constructor) so that PureComponent optimization can kick in, or you can implement your own shouldComponentUpdate and ignore the callback in the props comparison check.

You can also use Recompose library, which provide higher order components to achieve fine-tuned optimisations:

// A component that is expensive to render
const ExpensiveComponent = ({ propA, propB }) => {...}

// Optimized version of same component, using shallow comparison of props
// Same effect as React's PureRenderMixin
const OptimizedComponent = pure(ExpensiveComponent)

// Even more optimized: only updates if specific prop keys have changed
const HyperOptimizedComponent = onlyUpdateForKeys(['propA', 'propB'])(ExpensiveComponent)

In this case you could optimize the Child component by using:

const OptimizedChild = onlyUpdateForKeys(['text'])(Child)

How to advance to the next form input when the current input has a value?

you just need to give focus to the next input field (by invoking focus()method on that input element), for example if you're using jQuery this code will simulate the tab key when enter is pressed:

var inputs = $(':input').keypress(function(e){ 
    if (e.which == 13) {
       e.preventDefault();
       var nextInput = inputs.get(inputs.index(this) + 1);
       if (nextInput) {
          nextInput.focus();
       }
    }
});

Using an HTML button to call a JavaScript function

This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

enter image description here

Considering the particular column Amount in the above table is of integer type. The following would be a solution :

df['Amount'] = df.Amount.fillna(0).astype(int)

Similarly, you can fill it with various data types like float, str and so on.

In particular, I would consider datatype to compare various values of the same column.

C# refresh DataGridView when updating or inserted on another form

putting a quick example, should be a sufficient starting point

Code in Form A

public event EventHandler<EventArgs> RowAdded;

private void btnRowAdded_Click(object sender, EventArgs e)
{
     // insert data
     // if successful raise event
     OnRowAddedEvent();
}

private void OnRowAddedEvent()
{
     var listener = RowAdded;
     if (listener != null)
         listener(this, EventArgs.Empty);
}

Code in Form B

private void button1_Click(object sender, EventArgs e)
{
     var frm = new Form2();
     frm.RowAdded += new EventHandler<EventArgs>(frm_RowAdded);
     frm.Show();
}

void frm_RowAdded(object sender, EventArgs e)
{
     // retrieve data again
}

You can even consider creating your own EventArgs class that can contain the newly added data. You can then use this to directly add the data to a new row in DatagridView

What's the HTML to have a horizontal space between two objects?

CSS

div.horizontalgap {
  float: left;
  overflow: hidden;
  height: 1px;
  width: 0px;
}

Usage in HTML (for a 10px horizontal gap)

<div class="horizontalgap" style="width:10px"></div>

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

How to "properly" create a custom object in JavaScript?

In addition to the accepted answer from 2009. If you can can target modern browsers, one can make use of the Object.defineProperty.

The Object.defineProperty() method defines a new property directly on an object, or modifies an existing property on an object, and returns the object. Source: Mozilla

var Foo = (function () {
    function Foo() {
        this._bar = false;
    }
    Object.defineProperty(Foo.prototype, "bar", {
        get: function () {
            return this._bar;
        },
        set: function (theBar) {
            this._bar = theBar;
        },
        enumerable: true,
        configurable: true
    });
    Foo.prototype.toTest = function () {
        alert("my value is " + this.bar);
    };
    return Foo;
}());

// test instance
var test = new Foo();
test.bar = true;
test.toTest();

To see a desktop and mobile compatibility list, see Mozilla's Browser Compatibility list. Yes, IE9+ supports it as well as Safari mobile.

How to install PHP intl extension in Ubuntu 14.04

For php5 on Ubuntu 14.04

sudo apt-get install php5-intl

For php7 on Ubuntu 16.04

sudo apt-get install php7.0-intl

For php7.2 on Ubuntu 18.04

sudo apt-get install php7.2-intl

Anyway restart your apache after

sudo service apache2 restart

IMPORTANT NOTE: Keep in mind that your php in your terminal/command line has NOTHING todo with the php used by the apache webserver!

If the extension is already installed you should try to enable it. Either in the php.ini file or from command line.

Syntax:

php:

phpenmod [mod name]

apache:

a2enmod [mod name]

Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0

Somehow I had the wrong versions of the DLLs registered in my project.

  • I removed the three references to the Crystal Report dlls from my project. Crystal DLLs
  • I right click References, and click Add Reference
  • In the popup window, I click the Browse menu on the left and the Browse button Reference Manager
  • In the Directory window where your DLLs reside (perhaps your application's bin directory), select the three Crystal Reports DLLs and then click Add. DLLs
  • Back at the Reference Manager window, click in the first column to the left of the three Crystal dlls, and then click OK enter image description here
  • At this point your Crystal Reports should work again.

Detect & Record Audio in Python

I believe the WAVE module does not support recording, just processing existing files. You might want to look at PyAudio for actually recording. WAV is about the world's simplest file format. In paInt16 you just get a signed integer representing a level, and closer to 0 is quieter. I can't remember if WAV files are high byte first or low byte, but something like this ought to work (sorry, I'm not really a python programmer:

from array import array

# you'll probably want to experiment on threshold
# depends how noisy the signal
threshold = 10 
max_value = 0

as_ints = array('h', data)
max_value = max(as_ints)
if max_value > threshold:
    # not silence

PyAudio code for recording kept for reference:

import pyaudio
import sys

chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5

p = pyaudio.PyAudio()

stream = p.open(format=FORMAT,
                channels=CHANNELS, 
                rate=RATE, 
                input=True,
                output=True,
                frames_per_buffer=chunk)

print "* recording"
for i in range(0, 44100 / chunk * RECORD_SECONDS):
    data = stream.read(chunk)
    # check for silence here by comparing the level with 0 (or some threshold) for 
    # the contents of data.
    # then write data or not to a file

print "* done"

stream.stop_stream()
stream.close()
p.terminate()

SQL Server : Columns to Rows

well If you have 150 columns then I think that UNPIVOT is not an option. So you could use xml trick

;with CTE1 as (
    select ID, EntityID, (select t.* for xml raw('row'), type) as Data
    from temp1 as t
), CTE2 as (
    select
         C.id, C.EntityID,
         F.C.value('local-name(.)', 'nvarchar(128)') as IndicatorName,
         F.C.value('.', 'nvarchar(max)') as IndicatorValue
    from CTE1 as c
        outer apply c.Data.nodes('row/@*') as F(C)
)
select * from CTE2 where IndicatorName like 'Indicator%'

sql fiddle demo

You could also write dynamic SQL, but I like xml more - for dynamic SQL you have to have permissions to select data directly from table and that's not always an option.

UPDATE
As there a big flame in comments, I think I'll add some pros and cons of xml/dynamic SQL. I'll try to be as objective as I could and not mention elegantness and uglyness. If you got any other pros and cons, edit the answer or write in comments

cons

  • it's not as fast as dynamic SQL, rough tests gave me that xml is about 2.5 times slower that dynamic (it was one query on ~250000 rows table, so this estimate is no way exact). You could compare it yourself if you want, here's sqlfiddle example, on 100000 rows it was 29s (xml) vs 14s (dynamic);
  • may be it could be harder to understand for people not familiar with xpath;

pros

  • it's the same scope as your other queries, and that could be very handy. A few examples come to mind
    • you could query inserted and deleted tables inside your trigger (not possible with dynamic at all);
    • user don't have to have permissions on direct select from table. What I mean is if you have stored procedures layer and user have permissions to run sp, but don't have permissions to query tables directly, you still could use this query inside stored procedure;
    • you could query table variable you have populated in your scope (to pass it inside the dynamic SQL you have to either make it temporary table instead or create type and pass it as a parameter into dynamic SQL;
  • you can do this query inside the function (scalar or table-valued). It's not possible to use dynamic SQL inside the functions;

Putting text in top left corner of matplotlib plot

import matplotlib.pyplot as plt

plt.figure(figsize=(6, 6))
plt.text(0.1, 0.9, 'text', size=15, color='purple')

# or 

fig, axe = plt.subplots(figsize=(6, 6))
axe.text(0.1, 0.9, 'text', size=15, color='purple')

Output of Both

enter image description here

import matplotlib.pyplot as plt

# Build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
ax = plt.gca()
p = plt.Rectangle((left, bottom), width, height, fill=False)
p.set_transform(ax.transAxes)
p.set_clip_on(False)
ax.add_patch(p)


ax.text(left, bottom, 'left top',
        horizontalalignment='left',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, bottom, 'left bottom',
        horizontalalignment='left',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right bottom',
        horizontalalignment='right',
        verticalalignment='bottom',
        transform=ax.transAxes)

ax.text(right, top, 'right top',
        horizontalalignment='right',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(right, bottom, 'center top',
        horizontalalignment='center',
        verticalalignment='top',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'right center',
        horizontalalignment='right',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, 0.5 * (bottom + top), 'left center',
        horizontalalignment='left',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(0.5 * (left + right), 0.5 * (bottom + top), 'middle',
        horizontalalignment='center',
        verticalalignment='center',
        transform=ax.transAxes)

ax.text(right, 0.5 * (bottom + top), 'centered',
        horizontalalignment='center',
        verticalalignment='center',
        rotation='vertical',
        transform=ax.transAxes)

ax.text(left, top, 'rotated\nwith newlines',
        horizontalalignment='center',
        verticalalignment='center',
        rotation=45,
        transform=ax.transAxes)

plt.axis('off')

plt.show()

enter image description here

Copy row but with new id

THIS WORKS FOR DUPLICATING ONE ROW ONLY

  • Select your ONE row from your table
  • Fetch all associative
  • unset the ID row (Unique Index key)
  • Implode the array[0] keys into the column names
  • Implode the array[0] values into the column values
  • Run the query

The code:

 $qrystr = "SELECT * FROM mytablename  WHERE id= " . $rowid;
 $qryresult = $this->connection->query($qrystr);
 $result = $qryresult->fetchAll(PDO::FETCH_ASSOC);
 unset($result[0]['id']); //Remove ID from array
 $qrystr = " INSERT INTO mytablename";
 $qrystr .= " ( " .implode(", ",array_keys($result[0])).") ";
 $qrystr .= " VALUES ('".implode("', '",array_values($result[0])). "')";
 $result = $this->connection->query($qrystr);
 return $result;

Of course you should use PDO:bindparam and check your variables against attack, etc but gives the example

additional info

If you have a problem with handling NULL values, you can use following codes so that imploding names and values only for whose value is not NULL.

foreach ($result[0] as $index => $value) {
    if ($value === null) unset($result[0][$index]);
}

How to make the HTML link activated by clicking on the <li>?

#menu li { padding: 0px; }
#menu li a { margin: 0px; display: block; width: 100%; height: 100%; }

It may need some tweaking for IE6, but that's about how you do it.

BitBucket - download source as ZIP

In case you want to download the repo from your shell/terminal it should work like this:

wget https://user:[email protected]/user-name/repo-name/get/master.tar.bz2

or whatever download URL you might have.

Please make sure the user:password are both URL-encoded. So for instance if your username contains the @ symbol then replace it with %40.

Matching an empty input box using CSS

I realize this is a very old thread, but things have changed a bit since and it did help me find the right combination of things I needed to get my problem fixed. So I thought I'd share what I did.

The problem was I nedded to have the same css applied for an optional input if it was filled, as I had for a filled required. The css used the psuedo class :valid which applied the css on the optional input also when not filled.

This is how I fixed it;

HTML

<input type="text" required="required">
<input type="text" placeholder="">

CSS

input:required:valid {
    ....
}
input:optional::not(:placeholder-shown){
    ....
}

Set up adb on Mac OS X

This totally worked for me, after dickering around for a while after installing Android Studio:

  1. Make sure you have the .bash_profile file. This should be in your [username] directory.

  2. From whatever directory you are on, type this:

    echo "export PATH=\$PATH:/Users/${USER}/Library/Android/sdk/platform-tools/" >> ~/.bash_profile
    

Now, usually you will have this exact path, but if not, then use whatever path you have the platform-tools folder

  1. From the directory where your .bash_profile resides, type this:

    . .bash_profile
    
  2. Now type adb devices. You should see a "List of devices attached" response. Now you do not have to go to the platform-tools directory each and every time to type in the more cryptic command like, ./adb devices!!!

How to find and turn on USB debugging mode on Nexus 4

Looking for About Phone in Settings. And scroll down till you see Build number. Tap here till you see Toast message tell you have just enable developer mode.

Back to settings, you can see options: "Developer options"

git pull error "The requested URL returned error: 503 while accessing"

Every one please avoid modifying post buffer and advising it to others. It may help in some cases but it breaks others. If you have modified your post buffer for pushing your large project. Undo it using following command. git config --global --unset http.postBuffer git config --local --unset http.postBuffer

I modified my post buffer to fix one of the issues I had with git but it was the reason for my future problems with git.

Check if a input box is empty

If your textbox is a Required field and have some regex pattern to match and has minlength and maxlength

TestBox code

<input type="text" name="myfieldname" ng-pattern="/^[ A-Za-z0-9_@./#&+-]*$/" ng-minlength="3" ng-maxlength="50" class="classname" ng-model="model.myfieldmodel">

Ng-Class to Add

ng-class="{ 'err' :  myform.myfieldname.$invalid || (myform.myfieldname.$touched && !model.myfieldmodel.length) }"

How to convert an array to a string in PHP?

PHP has a built-in function implode to assign array values to string. Use it like this:

$str = implode(",", $array);

do-while loop in R

Building on the other answers, I wanted to share an example of using the while loop construct to achieve a do-while behaviour. By using a simple boolean variable in the while condition (initialized to TRUE), and then checking our actual condition later in the if statement. One could also use a break keyword instead of the continue <- FALSE inside the if statement (probably more efficient).

  df <- data.frame(X=c(), R=c())  
  x <- x0
  continue <- TRUE

  while(continue)
  {
    xi <- (11 * x) %% 16
    df <- rbind(df, data.frame(X=x, R=xi))
    x <- xi

    if(xi == x0)
    {
      continue <- FALSE
    }
  }

How to detect simple geometric shapes using OpenCV

The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.

Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:

double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer

Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.

Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.

In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis

PHP to search within txt file and echo the whole line

And a PHP example, multiple matching lines will be displayed:

<?php
$file = 'somefile.txt';
$searchfor = 'name';

// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');

// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
   echo "Found matches:\n";
   echo implode("\n", $matches[0]);
}
else{
   echo "No matches found";
}

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

Concatenate chars to form String in java

You can use StringBuilder:

    StringBuilder sb = new StringBuilder();
    sb.append('a');
    sb.append('b');
    sb.append('c');
    String str = sb.toString()

Or if you already have the characters, you can pass a character array to the String constructor:

String str = new String(new char[]{'a', 'b', 'c'});

Random integer in VB.NET

You should create a pseudo-random number generator only once:

Dim Generator As System.Random = New System.Random()

Then, if an integer suffices for your needs, you can use:

Public Function GetRandom(myGenerator As System.Random, ByVal Min As Integer, ByVal Max As Integer) As Integer
'min is inclusive, max is exclusive (dah!)
Return myGenerator.Next(Min, Max + 1)
End Function

as many times as you like. Using the wrapper function is justified only because the maximum value is exclusive - I know that the random numbers work this way but the definition of .Next is confusing.

Creating a generator every time you need a number is in my opinion wrong; the pseudo-random numbers do not work this way.

First, you get the problem with initialization which has been discussed in the other replies. If you initialize once, you do not have this problem.

Second, I am not at all certain that you get a valid sequence of random numbers; rather, you get a collection of the first number of multiple different sequences which are seeded automatically based on computer time. I am not certain that these numbers will pass the tests that confirm the randomness of the sequence.

Understanding the difference between Object.create() and new SomeFunction()

Let me try to explain (more on Blog) :

  1. When you write Car constructor var Car = function(){}, this is how things are internally: A diagram of prototypal chains when creating javascript objects We have one {prototype} hidden link to Function.prototype which is not accessible and one prototype link to Car.prototype which is accessible and has an actual constructor of Car. Both Function.prototype and Car.prototype have hidden links to Object.prototype.
  2. When we want to create two equivalent objects by using the new operator and create method then we have to do it like this: Honda = new Car(); and Maruti = Object.create(Car.prototype).A diagram of prototypal chains for differing object creation methods What is happening?

    Honda = new Car(); — When you create an object like this then hidden {prototype} property is pointed to Car.prototype. So here, the {prototype} of the Honda object will always be Car.prototype — we don't have any option to change the {prototype} property of the object. What if I want to change the prototype of our newly created object?
    Maruti = Object.create(Car.prototype) — When you create an object like this you have an extra option to choose your object's {prototype} property. If you want Car.prototype as the {prototype} then pass it as a parameter in the function. If you don't want any {prototype} for your object then you can pass null like this: Maruti = Object.create(null).

Conclusion — By using the method Object.create you have the freedom to choose your object {prototype} property. In new Car();, you don't have that freedom.

Preferred way in OO JavaScript :

Suppose we have two objects a and b.

var a = new Object();
var b = new Object();

Now, suppose a has some methods which b also wants to access. For that, we require object inheritance (a should be the prototype of b only if we want access to those methods). If we check the prototypes of a and b then we will find out that they share the prototype Object.prototype.

Object.prototype.isPrototypeOf(b); //true
a.isPrototypeOf(b); //false (the problem comes into the picture here).

Problem — we want object a as the prototype of b, but here we created object b with the prototype Object.prototype. Solution — ECMAScript 5 introduced Object.create(), to achieve such inheritance easily. If we create object b like this:

var b = Object.create(a);

then,

a.isPrototypeOf(b);// true (problem solved, you included object a in the prototype chain of object b.)

So, if you are doing object oriented scripting then Object.create() is very useful for inheritance.

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

How to install VS2015 Community Edition offline

You can download the ISO from https://beta.visualstudio.com/downloads/ (even if it has "beta" in the URL you'll have the latest stable version. Currently update 3)

VS2015 Community download

HTML&CSS + Twitter Bootstrap: full page layout or height 100% - Npx

Is this what you are looking for? Here is a fiddle demo.

The layout is based on percentage, colors are for clarity. If the content column overflows, a scrollbar should appear.

body, html, .container-fluid {
  height: 100%;
}

.navbar {
  width:100%;
  background:yellow;
}

.article-tree {
  height:100%;
  width: 25%;
  float:left;
  background: pink;
}

.content-area {
  overflow: auto;
  height: 100%;
  background:orange;
}

.footer {
   background: red;
   width:100%;
   height: 20px;
}

Viewing my IIS hosted site on other machines on my network

You have to do following steps.

Go to IIS ->
Sites->
Click on Your Web site ->
In Action Click on Edit Permissions ->
Security ->
Click on ADD ->
Advanced ->
Find Now ->
Add all the users in it ->
and grant all permissions to other users ->
click on Ok.

If you do above things properly you can access your web site by using your domain.
Suggestion - Do not add host name to your site it creates problem sometime. So please host your web site using your machines ip address.

What is the maximum length of a valid email address?

An email address must not exceed 254 characters.

This was accepted by the IETF following submitted erratum. A full diagnosis of any given address is available online. The original version of RFC 3696 described 320 as the maximum length, but John Klensin subsequently accepted an incorrect value, since a Path is defined as

Path = "<" [ A-d-l ":" ] Mailbox ">"

So the Mailbox element (i.e., the email address) has angle brackets around it to form a Path, which a maximum length of 254 characters to restrict the Path length to 256 characters or fewer.

The maximum length specified in RFC 5321 states:

The maximum total length of a reverse-path or forward-path is 256 characters.

RFC 3696 was corrected here.

People should be aware of the errata against RFC 3696 in particular. Three of the canonical examples are in fact invalid addresses.

I've collated a couple hundred test addresses, which you can find at http://www.dominicsayers.com/isemail

Plot bar graph from Pandas DataFrame

To plot just a selection of your columns you can select the columns of interest by passing a list to the subscript operator:

ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)

What you tried was df['V1','V2'] this will raise a KeyError as correctly no column exists with that label, although it looks funny at first you have to consider that your are passing a list hence the double square brackets [[]].

import matplotlib.pyplot as plt
ax = df[['V1','V2']].plot(kind='bar', title ="V comp", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Hour", fontsize=12)
ax.set_ylabel("V", fontsize=12)
plt.show()

enter image description here

How do I use Wget to download all images into a single folder, from a URL?

Try this one:

wget -nd -r -P /save/location/ -A jpeg,jpg,bmp,gif,png http://www.domain.com

and wait until it deletes all extra information

Angular 5, HTML, boolean on checkbox is checked

Here is my answer,

In row.model.ts

export interface Row {
   otherProperty : type;
   checked : bool;
   otherProperty : type;
   ...
}

In .html

<tr class="even" *ngFor="let item of rows">
   <input [checked]="item.checked" type="checkbox">
</tr>

In .ts

rows : Row[] = [];

update the rows in component.ts

How should I store GUID in MySQL tables?

For those just stumbling across this, there is now a much better alternative as per research by Percona.

It consists of reorganising the UUID chunks for optimal indexing, then converting into binary for reduced storage.

Read the full article here

Relative imports in Python 3

I needed to run python3 from the main project directory to make it work.

For example, if the project has the following structure:

project_demo/
+-- main.py
+-- some_package/
¦   +-- __init__.py
¦   +-- project_configs.py
+-- test/
    +-- test_project_configs.py

Solution

I would run python3 inside folder project_demo/ and then perform a

from some_package import project_configs

Testing for empty or nil-value string

The second clause does not need a !variable.nil? check—if evaluation reaches that point, variable.nil is guaranteed to be false (because of short-circuiting).

This should be sufficient:

variable = id if variable.nil? || variable.empty?

If you're working with Ruby on Rails, Object.blank? solves this exact problem:

An object is blank if it’s false, empty, or a whitespace string. For example, "", " ", nil, [], and {} are all blank.

How does python numpy.where() work?

Old Answer it is kind of confusing. It gives you the LOCATIONS (all of them) of where your statment is true.

so:

>>> a = np.arange(100)
>>> np.where(a > 30)
(array([31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
       48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
       65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
       82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
       99]),)
>>> np.where(a == 90)
(array([90]),)

a = a*40
>>> np.where(a > 1000)
(array([26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
       43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
       60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
       77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
       94, 95, 96, 97, 98, 99]),)
>>> a[25]
1000
>>> a[26]
1040

I use it as an alternative to list.index(), but it has many other uses as well. I have never used it with 2D arrays.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

New Answer It seems that the person was asking something more fundamental.

The question was how could YOU implement something that allows a function (such as where) to know what was requested.

First note that calling any of the comparison operators do an interesting thing.

a > 1000
array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True`,  True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)`

This is done by overloading the "__gt__" method. For instance:

>>> class demo(object):
    def __gt__(self, item):
        print item


>>> a = demo()
>>> a > 4
4

As you can see, "a > 4" was valid code.

You can get a full list and documentation of all overloaded functions here: http://docs.python.org/reference/datamodel.html

Something that is incredible is how simple it is to do this. ALL operations in python are done in such a way. Saying a > b is equivalent to a.gt(b)!

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

Install the ASP.NET AJAX Control Toolkit

  1. Download the ZIP file AjaxControlToolkit-Framework3.5SP1-DllOnly.zip from the ASP.NET AJAX Control Toolkit Releases page of the CodePlex web site.

  2. Copy the contents of this zip file directly into the bin directory of your web site.

Update web.config

  1. Put this in your web.config under the <controls> section:

    <?xml version="1.0"?>
    <configuration>
        ...
        <system.web>
            ...
            <pages>
                ...
                <controls>
                    ...
                    <add tagPrefix="ajaxtoolkit"
                        namespace="AjaxControlToolkit"
                        assembly="AjaxControlToolKit"/>
                </controls>
            </pages>
            ...
        </system.web>
        ...
    </configuration>
    

Setup Visual Studio

  1. Right-click on the Toolbox and select "Add Tab", and add a tab called "AJAX Control Toolkit"

  2. Inside that tab, right-click on the Toolbox and select "Choose Items..."

  3. When the "Choose Toolbox Items" dialog appears, click the "Browse..." button. Navigate to your project's "bin" folder. Inside that folder, select "AjaxControlToolkit.dll" and click OK. Click OK again to close the Choose Items Dialog.

You can now use the controls in your web sites!

MySQL Delete all rows from table and reset ID to zero

If you cannot use TRUNCATE (e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:

ALTER TABLE mytable AUTO_INCREMENT = 1

Is Visual Studio Community a 30 day trial?

I had this problem. Signing in or pressing the "Check for an updated license" link did not work for me. My solution was to restart Visual Studio, try again (sign in and check for license). Restart Visual Studio, try again. I had to do this several times and then it worked! (I also tried pressing the "File" menu that is available for a short period of time before the annoying request window appears again.) Maybe you just don't get connected to the server or the server itself doesn't update its database fast enough.

How can a Javascript object refer to values in itself?

One alternative would be to use a getter/setter methods.

For instance, if you only care about reading the calculated value:

var book  = {}

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true },
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + " works!";
        }
    }
});

console.log(book.key2); //prints "it works!"

The above code, though, won't let you define another value for key2.

So, the things become a bit more complicated if you would like to also redefine the value of key2. It will always be a calculated value. Most likely that's what you want.

However, if you would like to be able to redefine the value of key2, then you will need a place to cache its value independently of the calculation.

Somewhat like this:

var book  = { _key2: " works!" }

Object.defineProperties(book,{
    key1: { value: "it", enumerable: true},
    _key2: { enumerable: false},
    key2: {
        enumerable: true,
        get: function(){
            return this.key1 + this._key2;
        },
        set: function(newValue){
            this._key2 = newValue;
        }
    }
});

console.log(book.key2); //it works!

book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!

for(var key in book){
    //prints both key1 and key2, but not _key2
    console.log(key + ":" + book[key]); 
}

Another interesting alternative is to use a self-initializing object:

var obj = ({
  x: "it",
  init: function(){
    this.y = this.x + " works!";
    return this;
  }
}).init();

console.log(obj.y); //it works!

Python: SyntaxError: non-keyword after keyword arg

To really get this clear, here's my for-beginners answer: You inputed the arguments in the wrong order.
A keyword argument has this style:

nullable=True, unique=False

A fixed parameter should be defined: True, False, etc. A non-keyword argument is different:

name="Ricardo", fruit="chontaduro" 

This syntax error asks you to first put name="Ricardo" and all of its kind (non-keyword) before those like nullable=True.

how to draw directed graphs using networkx in python?

Fully fleshed out example with arrows for only the red edges:

import networkx as nx
import matplotlib.pyplot as plt

G = nx.DiGraph()
G.add_edges_from(
    [('A', 'B'), ('A', 'C'), ('D', 'B'), ('E', 'C'), ('E', 'F'),
     ('B', 'H'), ('B', 'G'), ('B', 'F'), ('C', 'G')])

val_map = {'A': 1.0,
           'D': 0.5714285714285714,
           'H': 0.0}

values = [val_map.get(node, 0.25) for node in G.nodes()]

# Specify the edges you want here
red_edges = [('A', 'C'), ('E', 'C')]
edge_colours = ['black' if not edge in red_edges else 'red'
                for edge in G.edges()]
black_edges = [edge for edge in G.edges() if edge not in red_edges]

# Need to create a layout when doing
# separate calls to draw nodes and edges
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, cmap=plt.get_cmap('jet'), 
                       node_color = values, node_size = 500)
nx.draw_networkx_labels(G, pos)
nx.draw_networkx_edges(G, pos, edgelist=red_edges, edge_color='r', arrows=True)
nx.draw_networkx_edges(G, pos, edgelist=black_edges, arrows=False)
plt.show()

Red edges

upstream sent too big header while reading response header from upstream

Add:

fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;
proxy_buffer_size   128k;
proxy_buffers   4 256k;
proxy_busy_buffers_size   256k;

To server{} in nginx.conf

Works for me.

Format a BigDecimal as String with max 2 decimal digits, removing 0 on decimal part

If its money use:

NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)

jQuery AJAX Call to PHP Script with JSON Return

Your datatype is wrong, change datatype for dataType.

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

In your particular case the issue seem to be with accessing the site from non-canonical url (www.site.com vs. site.com).

Instead of fixing CORS issue (which may require writing proxy to server fonts with proper CORS headers depending on service provider) you can normalize your Urls to always server content on canonical Url and simply redirect if one requests page without "www.".

Alternatively you can upload fonts to different server/CDN that is known to have CORS headers configured or you can easily do so.

How do I insert non breaking space character &nbsp; in a JSF page?

I found that the parser would complain if I used the &nbsp; entity in my page. After a little research, I learned that if I added a DOCTYPE declaration to the beginning of the page, the entity was allowed. I use this DOCTYPE declaration:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

A side effect of this is that the resulting code (as seen by using the "view source" feature of a web browser) doesn't actually contain the &nbsp; entity. It instead includes the actual characters that represent a nonbreaking space. Although it works, it's not really what I want. I'm still looking for a way to make the parser not replace the entity with the character.

More information here: http://java.net/jira/browse/JAVASERVERFACES-1576

How to multi-line "Replace in files..." in Notepad++

It's easy to do multiline replace in Notepad++. You have to use \n to represent the newline in your string, and it works for both search and replace strings. You have to make sure to select "Extended" search mode in the bottom left corner of the search window.

I found a good article describing the features here: http://markantoniou.blogspot.com/2008/06/notepad-how-to-use-regular-expressions.html

File Upload ASP.NET MVC 3.0

Giving complete Solution

First use input in .CShtml in MVC View

<input type="file" id="UploadImg" /></br>
<img id="imgPreview" height="200" width="200" />

Now call Ajax call

  $("#UploadImg").change(function () {
    var data = new FormData();
    var files = $("#UploadImg").get(0).files;
    if (files.length > 0) {
        data.append("MyImages", files[0]);
    }

    $.ajax({
        // url: "Controller/ActionMethod"
        url: "/SignUp/UploadFile",
        type: "POST",
        processData: false,
        contentType: false,
        data: data,
        success: function (response)
        {
            //code after success
            $("#UploadPhoto").val(response);
            $("#imgPreview").attr('src', '/Upload/' + response);
        },
        error: function (er) {
            //alert(er);
        }

    });
});

Controller Json Call

[HttpGet]
public JsonResult UploadFile()
    {
        string _imgname = string.Empty;
        if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
        {
            var pic = System.Web.HttpContext.Current.Request.Files["MyImages"];
            if (pic.ContentLength > 0)
            {
                var fileName = Path.GetFileName(pic.FileName);
                var _ext = Path.GetExtension(pic.FileName);

                _imgname = Guid.NewGuid().ToString();
                var _comPath = Server.MapPath("/MyFolder") + _imgname + _ext;
                _imgname = "img_" + _imgname + _ext;

                ViewBag.Msg = _comPath;
                var path = _comPath;
                tblAssignment assign = new tblAssignment();
                assign.Uploaded_Path = "/MyFolder" + _imgname + _ext;
                // Saving Image in Original Mode
                pic.SaveAs(path);
            }
        }
        return Json(Convert.ToString(_imgname), JsonRequestBehavior.AllowGet);
    }

What are the differences between Mustache.js and Handlebars.js?

You've pretty much nailed it, however Mustache templates can also be compiled.

Mustache is missing helpers and the more advanced blocks because it strives to be logicless. Handlebars' custom helpers can be very useful, but often end up introducing logic into your templates.

Mustache has many different compilers (JavaScript, Ruby, Python, C, etc.). Handlebars began in JavaScript, now there are projects like django-handlebars, handlebars.java, handlebars-ruby, lightncandy (PHP), and handlebars-objc.

How to get store information in Magento?

To get information about the current store from anywhere in Magento, use:

<?php
$store = Mage::app()->getStore();

This will give you a Mage_Core_Model_Store object, which has some of the information you need:

<?php
$name = $store->getName();

As for your other question about line number, I'm not sure what you mean. If you mean that you want to know what line number in the code you are on (for error handling, for instance), try:

<?php
$line      = __LINE__;
$file      = __FILE__;
$class     = __CLASS__;
$method    = __METHOD__;
$namespace = __NAMESPACE__;

Can you target <br /> with css?

BR generates a line-break and it is only a line-break. As this element has no content, there are only few styles that make sense to apply on it, like clear or position. You can set BR's border but you won't see it as it has no visual dimension.

If you like to visually separate two sentences, then you probably want to use the horizontal ruler which is intended for this goal. Since you cannot change the markup, I'm afraid using only CSS you cannot achieve this.

It seems, it has been already discussed on other forums. Extract from Re: Setting the height of a BR element using CSS:

[T]his leads to a somewhat odd status for BR in that on the one hand it is not being treated as a normal element, but instead as an instance of \A in generated content, but on the other hand it is being treated as a normal element in that (a limited subset of) CSS properties are being allowed on it.

I also found a clarification in the CSS 1 specification (no higher level spec mentions it):

The current CSS1 properties and values cannot describe the behavior of the ‘BR’ element. In HTML, the ‘BR’ element specifies a line break between words. In effect, the element is replaced by a line break. Future versions of CSS may handle added and replaced content, but CSS1-based formatters must treat ‘BR’ specially.

Grant Wagner's tests show that there is no way to style BR as you can do with other elements. There is also a site online where you can test the results in your browser.

Update

pelms made some further investigations, and pointed out that IE8 (on Win7) and Chrome 2/Safari 4b allows you to style BR somewhat. And indeed, I checked the IE demo page with IE Net Renderer's IE8 engine, and it worked.

Update 2 c69 made some further investigations, and it turns out you can style the marker for br quite heavily (though, not cross-browser), yet this will not affect the line-break itself, because it seem to belong to parent container.

How to add a line break in an Android TextView?

Tried all the above, did some research of my own resulting in the following solution for rendering linefeed escape chars:

string = string.replace("\\\n", System.getProperty("line.separator"));
  1. Using the replace method you need to filter escaped linefeeds (e.g. '\\n')

  2. Only then each instance of line feed '\n' escape chars gets rendered into the actual linefeed

For this example I used a Google Apps Scripting noSQL database (ScriptDb) with JSON formatted data.

Cheers :D

Exit from app when click button in android phonegap?

if(navigator.app){
        navigator.app.exitApp();
}else if(navigator.device){
        navigator.device.exitApp();
}

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.

Change column type in pandas

Here is a function that takes as its arguments a DataFrame and a list of columns and coerces all data in the columns to numbers.

# df is the DataFrame, and column_list is a list of columns as strings (e.g ["col1","col2","col3"])
# dependencies: pandas

def coerce_df_columns_to_numeric(df, column_list):
    df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')

So, for your example:

import pandas as pd

def coerce_df_columns_to_numeric(df, column_list):
    df[column_list] = df[column_list].apply(pd.to_numeric, errors='coerce')

a = [['a', '1.2', '4.2'], ['b', '70', '0.03'], ['x', '5', '0']]
df = pd.DataFrame(a, columns=['col1','col2','col3'])

coerce_df_columns_to_numeric(df, ['col2','col3'])

What are the differences between json and simplejson Python modules?

simplejson module is simply 1,5 times faster than json (On my computer, with simplejson 2.1.1 and Python 2.7 x86).

If you want, you can try the benchmark: http://abral.altervista.org/jsonpickle-bench.zip On my PC simplejson is faster than cPickle. I would like to know also your benchmarks!

Probably, as said Coady, the difference between simplejson and json is that simplejson includes _speedups.c. So, why don't python developers use simplejson?

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)

UPDATE

Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

Factorial in numpy and scipy

    from numpy import prod

    def factorial(n):
        print prod(range(1,n+1))

or with mul from operator:

    from operator import mul

    def factorial(n):
        print reduce(mul,range(1,n+1))

or completely without help:

    def factorial(n):
        print reduce((lambda x,y: x*y),range(1,n+1))

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

How to always show scrollbar

Since neither of the above worked for me, here's what did: android:scrollbarDefaultDelayBeforeFade="500000"

C#: Dynamic runtime cast

Try a generic:

public static T CastTo<T>(this dynamic obj, bool safeCast) where T:class
{
   try
   {
      return (T)obj;
   }
   catch
   {
      if(safeCast) return null;
      else throw;
   }
}

This is in extension method format, so its usage would be as if it were a member of dynamic objects:

dynamic myDynamic = new Something();
var typedObject = myDynamic.CastTo<Something>(false);

EDIT: Grr, didn't see that. Yes, you could reflectively close the generic, and it wouldn't be hard to hide in a non-generic extension method:

public static dynamic DynamicCastTo(this dynamic obj, Type castTo, bool safeCast)
{
   MethodInfo castMethod = this.GetType().GetMethod("CastTo").MakeGenericMethod(castTo);
   return castMethod.Invoke(null, new object[] { obj, safeCast });
}

I'm just not sure what you'd get out of this. Basically you're taking a dynamic, forcing a cast to a reflected type, then stuffing it back in a dynamic. Maybe you're right, I shouldn't ask. But, this'll probably do what you want. Basically when you go into dynamic-land, you lose the need to perform most casting operations as you can discover what an object is and does through reflective methods or trial and error, so there aren't many elegant ways to do this.

What's the best way to determine the location of the current PowerShell script?

For PowerShell 3.0

$PSCommandPath
    Contains the full path and file name of the script that is being run. 
    This variable is valid in all scripts.

The function is then:

function Get-ScriptDirectory {
    Split-Path -Parent $PSCommandPath
}

How can I commit files with git?

It sounds as if the only problem here is that the default editor that is launched is vi or vim, with which you're not familiar. (As quick tip, to exit that editor without saving changes, hit Esc a few times and then type :, q, ! and Enter.)

There are several ways to set up your default editor, and you haven't indicated which operating system you're using, so it's difficult to recommend one in particular. I'd suggest using:

 git config --global core.editor "name-of-your-editor"

... which sets a global git preference for a particular editor. Alternatively you can set the $EDITOR environment variable.

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I like the solution with qt.conf.

Put qt.conf near to the executable with next lines:

[Paths]
Prefix = /path/to/qtbase

And it works like a charm :^)

For a working example:

[Paths]
Prefix = /home/user/SDKS/Qt/5.6.2/5.6/gcc_64/

The documentation on this is here: https://doc.qt.io/qt-5/qt-conf.html

"No X11 DISPLAY variable" - what does it mean?

If you're on the main display, then

export DISPLAY=:0.0

or if you're using csh or tcsh

setenv DISPLAY :0.0

before running your app.

Actually, I'm surprised it isn't set automatically. Are you trying to start this application from a non-graphic terminal? If not, have you modified the default .profile, .login, .bashrc or .cshrc?

Note that setting the DISPLAY to :0.0 pre-supposes that you're sitting at the main display, as I said, or at least that the main display is logged on to your user id. If it's not logged on, or it's a different userid, this will fail.

If you're coming in from another machine, and you're at the main display of that machine and it's running X, then you can use "ssh -X hostname" to connect to that host, and ssh will forward the X display back. ssh will also make sure that the DISPLAY environment variable is set correctly (providing it isn't being messed with in the various dot files I mentioned above). In a "ssh -X" session, the DISPLAY environment variable will have a value like "localhost:11.0", which will point to the socket that ssh is tunnelling to your local box.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Today I have the similar problem.

Previous in my project gradle

// Top-level build file where you can add configuration options common to all 
sub-projects/modules.
allprojects {
repositories {
    jcenter()
    google()
    mavenCentral()
    maven { url "https://jitpack.io" }
    maven { url 'https://plugins.gradle.org/m2/'}
}}

Then I just added this below line in allprojects

maven {
        url "https://maven.google.com"
    }

It saved my day.

And now my current allproject {} code looks like this

allprojects {
repositories {
    jcenter()
    google()
    mavenCentral()
    maven { url "https://jitpack.io" }
    maven { url 'https://plugins.gradle.org/m2/'}
    maven {
        url "https://maven.google.com"
    }
}}

Microsoft.Office.Core Reference Missing

Have you actually gone to your references and added a .NET reference to the 'Microsoft.Office.Core' library? If you downloaded the example application, the answer would be yes. If that is the case, follow the advice in the article:

If your system does not have Microsoft Office Outlook 2003 you may have to change the References used by the "OutlookConnector" project. That is to say, if you received a build error described as "The type of namespace name 'Outlook' could not be found", you probably don't have Office 2003. Simply expand the project references, remove the afflicted items, and add the COM Library appropriate for your system. If someone has a dynamic way to handle this, I'd be curious to see you've done.

That should solve your problem. If not, let us know.

setTimeout in React Native

You can bind this to your function by adding .bind(this) directly to the end of your function definition. You would rewrite your code block as:

setTimeout(function () {
  this.setState({ timePassed: true });
}.bind(this), 1000);

how to get yesterday's date in C#

Something like this should work

var yesterday = DateTime.Now.Date.AddDays(-1);

DateTime.Now gives you the current date and time.

If your looking to remove the the time element then adding .Date constrains it to the date only ie time is 00:00:00.

Finally .AddDays(-1) removes 1 day to give you yesterday.

Use <Image> with a local file

You have to add to the source property an object with a property called "uri" where you can specify the path of your image as you can see in the following example:

<Image style={styles.image} source={{uri: "http://www.mysyte.com/myimage.jpg"}} />

remember then to set the width and height via the style property:

var styles = StyleSheet.create({
   image:{
    width: 360,
    height: 40,
  }
});

C++ array initialization

You can declare the array in C++ in these type of ways. If you know the array size then you should declare the array for: integer: int myArray[array_size]; Double: double myArray[array_size]; Char and string : char myStringArray[array_size]; The difference between char and string is as follows

char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";

If you don't know the size of array then you should leave the array blank like following.

integer: int myArray[array_size];

Double: double myArray[array_size];

How to disable Django's CSRF validation?

@WoooHaaaa some third party packages use 'django.middleware.csrf.CsrfViewMiddleware' middleware. for example i use django-rest-oauth and i have problem like you even after disabling those things. maybe these packages responded to your request like my case, because you use authentication decorator and something like this.

Java Returning method which returns arraylist?

Assuming you have something like so:

public class MyFirstClass {
   ...
   public ArrayList<Integer> myNumbers()    {
    ArrayList<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(11);
    numbers.add(3);
    return(numbers);
   }
   ...
}

You can call that method like so:

public class MySecondClass {
    ...
    MyFirstClass m1 = new MyFirstClass();
    List<Integer> myList = m1.myNumbers();
    ...
}

Since the method you are trying to call is not static, you will have to create an instance of the class which provides this method. Once you create the instance, you will then have access to the method.

Note, that in the code example above, I used this line: List<Integer> myList = m1.myNumbers();. This can be changed by the following: ArrayList<Integer> myList = m1.myNumbers();. However, it is usually recommended to program to an interface, and not to a concrete implementation, so my suggestion for the method you are using would be to do something like so:

public List<Integer> myNumbers()    {
    List<Integer> numbers = new ArrayList<Integer>();
    numbers.add(5);
    numbers.add(11);
    numbers.add(3);
    return(numbers);
   }

This will allow you to assign the contents of that list to whatever implements the List interface.

Setting environment variables on OS X

The $PATH variable is also subject to path_helper, which in turn makes use of the /etc/paths file and files in /etc/paths.d.

A more thorough description can be found in PATH and other environment issues in Leopard (2008-11)

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

 protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {  
        if (requestCode == CAMERE_REQUEST && resultCode == RESULT_OK && data != null) 
        {  
           Bitmap photo = (Bitmap) data.getExtras().get("data"); 
           imageView.setImageBitmap(photo);
        } 
}

You can check if the resultCode equals RESULT_OK this will only be the case if a picture is taken and selected and everything worked. This if clause here should check every condition.

Laravel PHP Command Not Found

Composer should be installed globally: Run this in your terminal:

    mv composer.phar /usr/local/bin/composer

Now composer commands will work.

The OutputPath property is not set for this project

This happened to me because I had moved the following line close to the beginning of the .csproj file:

  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets"/>

It needs to be placed after the PropertyGroups that define your Configuration|Platform.

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regex only allows exactly 8 characters. Use {8,} to specify eight or more instead of {8}.

But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone within minutes.

How to change MenuItem icon in ActionBar programmatically

This works for me. It should be in your onOptionsItemSelected(MenuItem item) method item.setIcon(R.drawable.your_icon);

Using Razor within JavaScript

What specific errors are you seeing?

Something like this could work better:

<script type="text/javascript">

//now add markers
 @foreach (var item in Model) {
    <text>
      var markerlatLng = new google.maps.LatLng(@Model.Latitude, @Model.Longitude);
      var title = '@(Model.Title)';
      var description = '@(Model.Description)';
      var contentString = '<h3>' + title + '</h3>' + '<p>' + description + '</p>'
    </text>
}
</script>

Note that you need the magical <text> tag after the foreach to indicate that Razor should switch into markup mode.

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

How do I mock a static method that returns void with PowerMock?

You can stub a static void method like this:

PowerMockito.doNothing().when(StaticResource.class, "getResource", anyString());

Although I'm not sure why you would bother, because when you call mockStatic(StaticResource.class) all static methods in StaticResource are by default stubbed

More useful, you can capture the value passed to StaticResource.getResource() like this:

ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
PowerMockito.doNothing().when(
               StaticResource.class, "getResource", captor.capture());

Then you can evaluate the String that was passed to StaticResource.getResource like this:

String resourceName = captor.getValue();

phpMyAdmin - config.inc.php configuration?

Run This Query:


*> -- --------------------------------------------------------
> -- SQL Commands to set up the pmadb as described in the documentation.
> --
> -- This file is meant for use with MySQL 5 and above!
> --
> -- This script expects the user pma to already be existing. If we would put a
> -- line here to create him too many users might just use this script and end
> -- up with having the same password for the controluser.
> --
> -- This user "pma" must be defined in config.inc.php (controluser/controlpass)
> --
> -- Please don't forget to set up the tablenames in config.inc.php
> --
> 
> -- --------------------------------------------------------
> 
> --
> -- Database : `phpmyadmin`
> -- CREATE DATABASE IF NOT EXISTS `phpmyadmin`   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin; USE phpmyadmin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Privileges
> --
> -- (activate this statement if necessary)
> -- GRANT SELECT, INSERT, DELETE, UPDATE, ALTER ON `phpmyadmin`.* TO
> --    'pma'@localhost;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__bookmark`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__bookmark` (   `id` int(10) unsigned
> NOT NULL auto_increment,   `dbase` varchar(255) NOT NULL default '',  
> `user` varchar(255) NOT NULL default '',   `label` varchar(255)
> COLLATE utf8_general_ci NOT NULL default '',   `query` text NOT NULL, 
> PRIMARY KEY  (`id`) )   COMMENT='Bookmarks'   DEFAULT CHARACTER SET
> utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__column_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__column_info` (   `id` int(5) unsigned
> NOT NULL auto_increment,   `db_name` varchar(64) NOT NULL default '', 
> `table_name` varchar(64) NOT NULL default '',   `column_name`
> varchar(64) NOT NULL default '',   `comment` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `mimetype` varchar(255) COLLATE
> utf8_general_ci NOT NULL default '',   `transformation` varchar(255)
> NOT NULL default '',   `transformation_options` varchar(255) NOT NULL
> default '',   `input_transformation` varchar(255) NOT NULL default '',
> `input_transformation_options` varchar(255) NOT NULL default '',  
> PRIMARY KEY  (`id`),   UNIQUE KEY `db_name`
> (`db_name`,`table_name`,`column_name`) )   COMMENT='Column information
> for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__history`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__history` (   `id` bigint(20) unsigned
> NOT NULL auto_increment,   `username` varchar(64) NOT NULL default '',
> `db` varchar(64) NOT NULL default '',   `table` varchar(64) NOT NULL
> default '',   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP,   `sqlquery` text NOT NULL,   PRIMARY KEY  (`id`), 
> KEY `username` (`username`,`db`,`table`,`timevalue`) )   COMMENT='SQL
> history for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__pdf_pages`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__pdf_pages` (   `db_name` varchar(64)
> NOT NULL default '',   `page_nr` int(10) unsigned NOT NULL
> auto_increment,   `page_descr` varchar(50) COLLATE utf8_general_ci NOT
> NULL default '',   PRIMARY KEY  (`page_nr`),   KEY `db_name`
> (`db_name`) )   COMMENT='PDF relation pages for phpMyAdmin'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__recent`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__recent` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Recently accessed tables'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__favorite`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__favorite` (   `username` varchar(64)
> NOT NULL,   `tables` text NOT NULL,   PRIMARY KEY (`username`) )  
> COMMENT='Favorite tables'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_uiprefs`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_uiprefs` (   `username`
> varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,   `table_name`
> varchar(64) NOT NULL,   `prefs` text NOT NULL,   `last_update`
> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
> CURRENT_TIMESTAMP,   PRIMARY KEY (`username`,`db_name`,`table_name`) )
> COMMENT='Tables'' UI preferences'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__relation`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__relation` (   `master_db` varchar(64)
> NOT NULL default '',   `master_table` varchar(64) NOT NULL default '',
> `master_field` varchar(64) NOT NULL default '',   `foreign_db`
> varchar(64) NOT NULL default '',   `foreign_table` varchar(64) NOT
> NULL default '',   `foreign_field` varchar(64) NOT NULL default '',  
> PRIMARY KEY  (`master_db`,`master_table`,`master_field`),   KEY
> `foreign_field` (`foreign_db`,`foreign_table`) )   COMMENT='Relation
> table'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_coords`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_coords` (   `db_name`
> varchar(64) NOT NULL default '',   `table_name` varchar(64) NOT NULL
> default '',   `pdf_page_number` int(11) NOT NULL default '0',   `x`
> float unsigned NOT NULL default '0',   `y` float unsigned NOT NULL
> default '0',   PRIMARY KEY  (`db_name`,`table_name`,`pdf_page_number`)
> )   COMMENT='Table coordinates for phpMyAdmin PDF output'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__table_info`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__table_info` (   `db_name` varchar(64)
> NOT NULL default '',   `table_name` varchar(64) NOT NULL default '',  
> `display_field` varchar(64) NOT NULL default '',   PRIMARY KEY 
> (`db_name`,`table_name`) )   COMMENT='Table information for
> phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__tracking`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__tracking` (   `db_name` varchar(64)
> NOT NULL,   `table_name` varchar(64) NOT NULL,   `version` int(10)
> unsigned NOT NULL,   `date_created` datetime NOT NULL,  
> `date_updated` datetime NOT NULL,   `schema_snapshot` text NOT NULL,  
> `schema_sql` text,   `data_sql` longtext,   `tracking`
> set('UPDATE','REPLACE','INSERT','DELETE','TRUNCATE','CREATE
> DATABASE','ALTER DATABASE','DROP DATABASE','CREATE TABLE','ALTER
> TABLE','RENAME TABLE','DROP TABLE','CREATE INDEX','DROP INDEX','CREATE
> VIEW','ALTER VIEW','DROP VIEW') default NULL,   `tracking_active`
> int(1) unsigned NOT NULL default '1',   PRIMARY KEY 
> (`db_name`,`table_name`,`version`) )   COMMENT='Database changes
> tracking for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__userconfig`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__userconfig` (   `username`
> varchar(64) NOT NULL,   `timevalue` timestamp NOT NULL default
> CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,   `config_data` text
> NOT NULL,   PRIMARY KEY  (`username`) )   COMMENT='User preferences
> storage for phpMyAdmin'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__users`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__users` (   `username` varchar(64) NOT
> NULL,   `usergroup` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`usergroup`) )   COMMENT='Users and their assignments to
> user groups'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__usergroups`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__usergroups` (   `usergroup`
> varchar(64) NOT NULL,   `tab` varchar(64) NOT NULL,   `allowed`
> enum('Y','N') NOT NULL DEFAULT 'N',   PRIMARY KEY
> (`usergroup`,`tab`,`allowed`) )   COMMENT='User groups with configured
> menu items'   DEFAULT CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__navigationhiding`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__navigationhiding` (   `username`
> varchar(64) NOT NULL,   `item_name` varchar(64) NOT NULL,  
> `item_type` varchar(64) NOT NULL,   `db_name` varchar(64) NOT NULL,  
> `table_name` varchar(64) NOT NULL,   PRIMARY KEY
> (`username`,`item_name`,`item_type`,`db_name`,`table_name`) )  
> COMMENT='Hidden items of navigation tree'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__savedsearches`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__savedsearches` (   `id` int(5)
> unsigned NOT NULL auto_increment,   `username` varchar(64) NOT NULL
> default '',   `db_name` varchar(64) NOT NULL default '',  
> `search_name` varchar(64) NOT NULL default '',   `search_data` text
> NOT NULL,   PRIMARY KEY  (`id`),   UNIQUE KEY
> `u_savedsearches_username_dbname` (`username`,`db_name`,`search_name`)
> )   COMMENT='Saved searches'   DEFAULT CHARACTER SET utf8 COLLATE
> utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__central_columns`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__central_columns` (   `db_name`
> varchar(64) NOT NULL,   `col_name` varchar(64) NOT NULL,   `col_type`
> varchar(64) NOT NULL,   `col_length` text,   `col_collation`
> varchar(64) NOT NULL,   `col_isNull` boolean NOT NULL,   `col_extra`
> varchar(255) default '',   `col_default` text,   PRIMARY KEY
> (`db_name`,`col_name`) )   COMMENT='Central list of columns'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__designer_settings`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__designer_settings` (   `username`
> varchar(64) NOT NULL,   `settings_data` text NOT NULL,   PRIMARY KEY
> (`username`) )   COMMENT='Settings related to Designer'   DEFAULT
> CHARACTER SET utf8 COLLATE utf8_bin;
> 
> -- --------------------------------------------------------
> 
> --
> -- Table structure for table `pma__export_templates`
> --
> 
> CREATE TABLE IF NOT EXISTS `pma__export_templates` (   `id` int(5)
> unsigned NOT NULL AUTO_INCREMENT,   `username` varchar(64) NOT NULL,  
> `export_type` varchar(10) NOT NULL,   `template_name` varchar(64) NOT
> NULL,   `template_data` text NOT NULL,   PRIMARY KEY (`id`),   UNIQUE
> KEY `u_user_type_template` (`username`,`export_type`,`template_name`)
> )   COMMENT='Saved export templates'   DEFAULT CHARACTER SET utf8
> COLLATE utf8_bin;*

Open This File :

C:\xampp\phpMyAdmin\config.inc.php

Clear and Past this Code :

> --------------------------------------------------------- <?php /**  * Debian local configuration file  *  * This file overrides the settings
> made by phpMyAdmin interactive setup  * utility.  *  * For example
> configuration see
> /usr/share/doc/phpmyadmin/examples/config.default.php.gz  *  * NOTE:
> do not add security sensitive data to this file (like passwords)  *
> unless you really know what you're doing. If you do, any user that can
> * run PHP or CGI on your webserver will be able to read them. If you still  * want to do this, make sure to properly secure the access to
> this file  * (also on the filesystem level).  */ /**  * Server(s)
> configuration  */ $i = 0; // The $cfg['Servers'] array starts with
> $cfg['Servers'][1].  Do not use $cfg['Servers'][0]. // You can disable
> a server config entry by setting host to ''. $i++; /* Read
> configuration from dbconfig-common */
> require('/etc/phpmyadmin/config-db.php'); /* Configure according to
> dbconfig-common if enabled */ if (!empty($dbname)) {
>     /* Authentication type */
>     $cfg['Servers'][$i]['auth_type'] = 'cookie';
>     /* Server parameters */
>     if (empty($dbserver)) $dbserver = 'localhost';
>     $cfg['Servers'][$i]['host'] = $dbserver;
>     if (!empty($dbport)) {
>         $cfg['Servers'][$i]['connect_type'] = 'tcp';
>         $cfg['Servers'][$i]['port'] = $dbport;
>     }
>     //$cfg['Servers'][$i]['compress'] = false;
>     /* Select mysqli if your server has it */
>     $cfg['Servers'][$i]['extension'] = 'mysqli';
>     /* Optional: User for advanced features */
>     $cfg['Servers'][$i]['controluser'] = $dbuser;
>     $cfg['Servers'][$i]['controlpass'] = $dbpass;
>     /* Optional: Advanced phpMyAdmin features */
>     $cfg['Servers'][$i]['pmadb'] = $dbname;
>     $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
>     $cfg['Servers'][$i]['relation'] = 'pma_relation';
>     $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
>     $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
>     $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
>     $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
>     $cfg['Servers'][$i]['history'] = 'pma_history';
>     $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
>     /* Uncomment the following to enable logging in to passwordless accounts,
>      * after taking note of the associated security risks. */
>     // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
>     /* Advance to next server for rest of config */
>     $i++; } /* Authentication type */ //$cfg['Servers'][$i]['auth_type'] = 'cookie'; /* Server parameters */
> $cfg['Servers'][$i]['host'] = 'localhost';  
> $cfg['Servers'][$i]['connect_type'] = 'tcp';
> //$cfg['Servers'][$i]['compress'] = false; /* Select mysqli if your
> server has it */ //$cfg['Servers'][$i]['extension'] = 'mysql'; /*
> Optional: User for advanced features */ //
> $cfg['Servers'][$i]['controluser'] = 'pma'; //
> $cfg['Servers'][$i]['controlpass'] = 'pmapass'; /* Optional: Advanced
> phpMyAdmin features */ // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
> // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark'; //
> $cfg['Servers'][$i]['relation'] = 'pma_relation'; //
> $cfg['Servers'][$i]['table_info'] = 'pma_table_info'; //
> $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords'; //
> $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages'; //
> $cfg['Servers'][$i]['column_info'] = 'pma_column_info'; //
> $cfg['Servers'][$i]['history'] = 'pma_history'; //
> $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords'; /*
> Uncomment the following to enable logging in to passwordless accounts,
> * after taking note of the associated security risks. */ // $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; /*  * End of servers
> configuration  */ /*  * Directories for saving/loading files from
> server  */ $cfg['UploadDir'] = ''; $cfg['SaveDir'] = '';

------------------------------------------

i Solve My Problem Through this Method

Open a new tab on button click in AngularJS

You should use the $location service

Angular docs:

How to disable back swipe gesture in UINavigationController on iOS 7

I found a solution:

Objective-C:

if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}

Swift 3+:
self.navigationController?.interactivePopGestureRecognizer?.isEnabled = false

Access 2010 VBA query a table and iterate through results

I know some things have changed in AC 2010. However, the old-fashioned ADODB is, as far as I know, the best way to go in VBA. An Example:

Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset
Dim colReturn As New Collection

Dim SQL As String
SQL = _
    "SELECT c.ClientID, c.LastName, c.FirstName, c.MI, c.DOB, c.SSN, " & _
    "c.RaceID, c.EthnicityID, c.GenderID, c.Deleted, c.RecordDate " & _
    "FROM tblClient AS c " & _
    "WHERE c.ClientID = @ClientID"

Set cn = New ADODB.Connection
Set cmd = New ADODB.Command

With cn
    .Provider = DataConnection.MyADOProvider
    .ConnectionString = DataConnection.MyADOConnectionString
    .Open
End With

With cmd
    .CommandText = SQL
    .ActiveConnection = cn
    Set prm = .CreateParameter("@ClientID", adInteger, adParamInput, , mlngClientID)
    .Parameters.Append prm
End With

Set rs = cmd.Execute

With rs
    If Not .EOF Then
        Do Until .EOF
            mstrLastName = Nz(!LastName, "")
            mstrFirstName = Nz(!FirstName, "")
            mstrMI = Nz(!MI, "")
            mdDOB = !DOB
            mstrSSN = Nz(!SSN, "")
            mlngRaceID = Nz(!RaceID, -1)
            mlngEthnicityID = Nz(!EthnicityID, -1)
            mlngGenderID = Nz(!GenderID, -1)
            mbooDeleted = Deleted
            mdRecordDate = Nz(!RecordDate, "")

            .MoveNext
        Loop
    End If
    .Close
End With

cn.Close

Set rs = Nothing
Set cn = Nothing

VueJs get url query

In my case I console.log(this.$route) and returned the fullPath:

console.js:
fullPath: "/solicitud/MX/666",
params: {market: "MX", id: "666"},
path: "/solicitud/MX/666"

console.js: /solicitud/MX/666

Find nearest value in numpy array

Here is a version with scipy for @Ari Onasafari, answer "to find the nearest vector in an array of vectors"

In [1]: from scipy import spatial

In [2]: import numpy as np

In [3]: A = np.random.random((10,2))*100

In [4]: A
Out[4]:
array([[ 68.83402637,  38.07632221],
       [ 76.84704074,  24.9395109 ],
       [ 16.26715795,  98.52763827],
       [ 70.99411985,  67.31740151],
       [ 71.72452181,  24.13516764],
       [ 17.22707611,  20.65425362],
       [ 43.85122458,  21.50624882],
       [ 76.71987125,  44.95031274],
       [ 63.77341073,  78.87417774],
       [  8.45828909,  30.18426696]])

In [5]: pt = [6, 30]  # <-- the point to find

In [6]: A[spatial.KDTree(A).query(pt)[1]] # <-- the nearest point 
Out[6]: array([  8.45828909,  30.18426696])

#how it works!
In [7]: distance,index = spatial.KDTree(A).query(pt)

In [8]: distance # <-- The distances to the nearest neighbors
Out[8]: 2.4651855048258393

In [9]: index # <-- The locations of the neighbors
Out[9]: 9

#then 
In [10]: A[index]
Out[10]: array([  8.45828909,  30.18426696])

isolating a sub-string in a string before a symbol in SQL Server 2008

DECLARE @test nvarchar(100)

SET @test = 'Foreign Tax Credit - 1997'

SELECT @test, left(@test, charindex('-', @test) - 2) AS LeftString,
    right(@test, len(@test) - charindex('-', @test) - 1)  AS RightString

Entity Framework .Remove() vs. .DeleteObject()

It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:

  • ObjectContext.DeleteObject(entity) marks the entity as Deleted in the context. (It's EntityState is Deleted after that.) If you call SaveChanges afterwards EF sends a SQL DELETE statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

  • EntityCollection.Remove(childEntity) marks the relationship between parent and childEntity as Deleted. If the childEntity itself is deleted from the database and what exactly happens when you call SaveChanges depends on the kind of relationship between the two:

    • If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL values, this foreign will be set to null and if you call SaveChanges this NULL value for the childEntity will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE statement. No DELETE statement occurs.

    • If the relationship is required (the FK doesn't allow NULL values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges - the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.

    • If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL) EF will mark the childEntity as Deleted as well. If you call SaveChanges a SQL DELETE statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.

I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)

Convert Python dict into a dataframe

I have run into this several times and have an example dictionary that I created from a function get_max_Path(), and it returns the sample dictionary:

{2: 0.3097502930247044, 3: 0.4413177909384636, 4: 0.5197224051562838, 5: 0.5717654946470984, 6: 0.6063959031223476, 7: 0.6365209824708223, 8: 0.655918861281035, 9: 0.680844386645206}

To convert this to a dataframe, I ran the following:

df = pd.DataFrame.from_dict(get_max_path(2), orient = 'index').reset_index()

Returns a simple two column dataframe with a separate index:

index 0 0 2 0.309750 1 3 0.441318

Just rename the columns using f.rename(columns={'index': 'Column1', 0: 'Column2'}, inplace=True)

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

According to your need this pattern should work just fine. Try this,

^(?=(.*\d){1})(.*\S)(?=.*[a-zA-Z\S])[0-9a-zA-Z\S]{8,}

Just create a string variable, assign the pattern, and create a boolean method which returns true if the pattern is correct, else false.

Sample:

String pattern = "^(?=(.*\d){1})(.*\S)(?=.*[a-zA-Z\S])[0-9a-zA-Z\S]{8,}";
String password_string = "Type the password here"

private boolean isValidPassword(String password_string) {
    return password_string.matches(Constants.passwordPattern);
}

Regular expression to limit number of characters to 10

/^[a-z]{0,10}$/ should work. /^[a-z]{1,10}$/ if you want to match at least one character, like /^[a-z]+$/ does.

How can I maintain fragment state when added to the back stack?

Public void replaceFragment(Fragment mFragment, int id, String tag, boolean addToStack) {
        FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
        mTransaction.replace(id, mFragment);
        hideKeyboard();
        if (addToStack) {
            mTransaction.addToBackStack(tag);
        }
        mTransaction.commitAllowingStateLoss();
    }
replaceFragment(new Splash_Fragment(), R.id.container, null, false);

Is it possible to output a SELECT statement from a PL/SQL block?

The classic “Hello World!” block contains an executable section that calls the DBMS_OUTPUT.PUT_LINE procedure to display text on the screen:

BEGIN
  DBMS_OUTPUT.put_line ('Hello World!');
END;

You can checkout it here: http://www.oracle.com/technetwork/issue-archive/2011/11-mar/o21plsql-242570.html

Can we import XML file into another XML file?

You could use an external (parsed) general entity.

You declare the entity like this:

<!ENTITY otherFile SYSTEM "otherFile.xml">

Then you reference it like this:

&otherFile;

A complete example:

<?xml version="1.0" standalone="no" ?>
<!DOCTYPE doc [
<!ENTITY otherFile SYSTEM "otherFile.xml">
]>
<doc>
  <foo>
    <bar>&otherFile;</bar>
  </foo>
</doc>

When the XML parser reads the file, it will expand the entity reference and include the referenced XML file as part of the content.

If the "otherFile.xml" contained: <baz>this is my content</baz>

Then the XML would be evaluated and "seen" by an XML parser as:

<?xml version="1.0" standalone="no" ?>
<doc>
  <foo>
    <bar><baz>this is my content</baz></bar>
  </foo>
</doc>

A few references that might be helpful:

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

Iterating over ResultSet and adding its value in an ArrayList

If I've understood your problem correctly, there are two possible problems here:

  • resultset is null - I assume that this can't be the case as if it was you'd get an exception in your while loop and nothing would be output.
  • The second problem is that resultset.getString(i++) will get columns 1,2,3 and so on from each subsequent row.

I think that the second point is probably your problem here.

Lets say you only had 1 row returned, as follows:

Col 1, Col 2, Col 3 
A    ,     B,     C

Your code as it stands would only get A - it wouldn't get the rest of the columns.

I suggest you change your code as follows:

ResultSet resultset = ...;
ArrayList<String> arrayList = new ArrayList<String>(); 
while (resultset.next()) {                      
    int i = 1;
    while(i <= numberOfColumns) {
        arrayList.add(resultset.getString(i++));
    }
    System.out.println(resultset.getString("Col 1"));
    System.out.println(resultset.getString("Col 2"));
    System.out.println(resultset.getString("Col 3"));                    
    System.out.println(resultset.getString("Col n"));
}

Edit:

To get the number of columns:

ResultSetMetaData metadata = resultset.getMetaData();
int numberOfColumns = metadata.getColumnCount();

HTML5 Email Validation

A bit late for the party, but this regular expression helped me to validate email type input in the client side. Though, we should always do verification in server side also.

<input type="email" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">

You can find more regex of all kinds here.

Remove shadow below actionbar

What is the style item to make it disappear?

In order to remove the shadow add this to your app theme:

<style name="MyAppTheme" parent="android:Theme.Holo.Light">
    <item name="android:windowContentOverlay">@null</item>
</style>

UPDATE: As @Quinny898 stated, on Android 5.0 this has changed, you have to call setElevation(0) on your action bar. Note that if you're using the support library you must call it to that like so:

getSupportActionBar().setElevation(0);

How to insert 1000 rows at a time

You can insert multiple records by inserting from a result:

insert into db (@names,@email,@password) 
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword' union all
select 'abc','def','mypassword'

Just add as many records you like. There may be limitations on the complexity of the query though, so it might not be possible to add as many as 1000 records at once.

How to convert unix timestamp to calendar date moment.js

UNIX timestamp it is count of seconds from 1970, so you need to convert it to JS Date object:

var date = new Date(unixTimestamp*1000);

Redirecting a request using servlets and the "setHeader" method not working

Oh no no! That's not how you redirect. It's far more simpler:

public class ModHelloWorld extends HttpServlet{
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.sendRedirect("http://www.google.com");
    }
}

Also, it's a bad practice to write HTML code within a servlet. You should consider putting all that markup into a JSP and invoking the JSP using:

response.sendRedirect("/path/to/mynewpage.jsp");

JavaScript equivalent of PHP’s die

It is possible to roll your own version of PHP's die:

function die(msg)
{
    throw msg;
}

function test(arg1)
{
    arg1 = arg1 || die("arg1 is missing"); 
}

test();

JSFiddle Example

Setting Django up to use MySQL

MySQL support is simple to add. In your DATABASES dictionary, you will have an entry like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

You also have the option of utilizing MySQL option files, as of Django 1.7. You can accomplish this by setting your DATABASES array like so:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'OPTIONS': {
            'read_default_file': '/path/to/my.cnf',
        },
    }
}

You also need to create the /path/to/my.cnf file with similar settings from above

[client]
database = DB_NAME
host = localhost
user = DB_USER
password = DB_PASSWORD
default-character-set = utf8

With this new method of connecting in Django 1.7, it is important to know the order connections are established:

1. OPTIONS.
2. NAME, USER, PASSWORD, HOST, PORT
3. MySQL option files.

In other words, if you set the name of the database in OPTIONS, this will take precedence over NAME, which would override anything in a MySQL option file.


If you are just testing your application on your local machine, you can use

python manage.py runserver

Adding the ip:port argument allows machines other than your own to access your development application. Once you are ready to deploy your application, I recommend taking a look at the chapter on Deploying Django on the djangobook

Mysql default character set is often not utf-8, therefore make sure to create your database using this sql:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

If you are using Oracle's MySQL connector your ENGINE line should look like this:

'ENGINE': 'mysql.connector.django',

Note that you will first need to install mysql on your OS.

brew install mysql (MacOS)

Also, the mysql client package has changed for python 3 (MySQL-Client works only for python 2)

pip3 install mysqlclient

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

           @Html.RadioButton("Insured.GenderType", 1, (Model.Insured.GenderType == 1 ))
           @Web.Mvc.Claims.Resources.PartyResource.MaleLabel
           @Html.RadioButton("Insured.GenderType", 2, Model.Insured.GenderType == 2)
           @Web.Mvc.Claims.Resources.PartyResource.FemaleLabel

How to encode a string in JavaScript for displaying in HTML?

Do not bother with encoding. Use a text node instead. Data in text node is guaranteed to be treated as text.

document.body.appendChild(document.createTextNode("Your&funky<text>here"))

How to get the index of an element in an IEnumerable?

An alternative to finding the index after the fact is to wrap the Enumerable, somewhat similar to using the Linq GroupBy() method.

public static class IndexedEnumerable
{
    public static IndexedEnumerable<T> ToIndexed<T>(this IEnumerable<T> items)
    {
        return IndexedEnumerable<T>.Create(items);
    }
}

public class IndexedEnumerable<T> : IEnumerable<IndexedEnumerable<T>.IndexedItem>
{
    private readonly IEnumerable<IndexedItem> _items;

    public IndexedEnumerable(IEnumerable<IndexedItem> items)
    {
        _items = items;
    }

    public class IndexedItem
    {
        public IndexedItem(int index, T value)
        {
            Index = index;
            Value = value;
        }

        public T Value { get; private set; }
        public int Index { get; private set; }
    }

    public static IndexedEnumerable<T> Create(IEnumerable<T> items)
    {
        return new IndexedEnumerable<T>(items.Select((item, index) => new IndexedItem(index, item)));
    }

    public IEnumerator<IndexedItem> GetEnumerator()
    {
        return _items.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Which gives a use case of:

var items = new[] {1, 2, 3};
var indexedItems = items.ToIndexed();
foreach (var item in indexedItems)
{
    Console.WriteLine("items[{0}] = {1}", item.Index, item.Value);
}

Microsoft Web API: How do you do a Server.MapPath?

I can't tell from the context you supply, but if it's something you just need to do at app startup, you can still use Server.MapPath in WebApiHttpApplication; e.g. in Application_Start().

I'm just answering your direct question; the already-mentioned HostingEnvironment.MapPath() is probably the preferred solution.

Call a global variable inside module

If You want to have a reference to this variable across the whole project, create somewhere d.ts file, e.g. globals.d.ts. Fill it with your global variables declarations, e.g.:

declare const BootBox: 'boot' | 'box';

Now you can reference it anywhere across the project, just like that:

const bootbox = BootBox;

Here's an example.

DB2 Query to retrieve all table names for a given schema

IN db2warehouse I found that "owner" doesn't exist, so I describe table syscat.systables and try using CREATOR instead and it works.

db2 "select NAME from sysibm.systables where CREATOR = '[SCHEMANAME]'and type = 'T'"

Stop absolutely positioned div from overlapping text

Put a z-indez of -1 on your absolute (or relative) positioned element.

This will pull it out of the stacking context. (I think.) Read more wonderful things about "stacking contexts" here: https://philipwalton.com/articles/what-no-one-told-you-about-z-index/

How to parse a JSON string into JsonNode in Jackson?

New approach to old question. A solution that works from java 9+

ObjectNode agencyNode = new ObjectMapper().valueToTree(Map.of("key", "value"));

is more readable and maintainable for complex objects. Ej

Map<String, Object> agencyMap = Map.of(
        "name", "Agencia Prueba",
        "phone1", "1198788373",
        "address", "Larrea 45 e/ calligaris y paris",
        "number", 267,
        "enable", true,
        "location", Map.of("id", 54),
        "responsible", Set.of(Map.of("id", 405)),
        "sellers", List.of(Map.of("id", 605))
);
ObjectNode agencyNode = new ObjectMapper().valueToTree(agencyMap);

How to multiply values using SQL

Why use GROUP BY at all?

SELECT player_name, player_salary, player_salary*1.1 AS NewSalary
FROM players
ORDER BY player_salary DESC

How can I get a web site's favicon?

You'll want to tackle this a few ways:

  1. Look for the favicon.ico at the root of the domain

    www.domain.com/favicon.ico

  2. Look for a <link> tag with the rel="shortcut icon" attribute

    <link rel="shortcut icon" href="/favicon.ico" />

  3. Look for a <link> tag with the rel="icon" attribute

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

The latter two will usually yield a higher quality image.


Just to cover all of the bases, there are device specific icon files that might yield higher quality images since these devices usually have larger icons on the device than a browser would need:

<link rel="apple-touch-icon" href="images/touch.png" />

<link rel="apple-touch-icon-precomposed" href="images/touch.png" />


And to download the icon without caring what the icon is you can use a utility like http://www.google.com/s2/favicons which will do all of the heavy lifting:

var client = new System.Net.WebClient();

client.DownloadFile(
    @"http://www.google.com/s2/favicons?domain=stackoverflow.com",
    "stackoverflow.com.ico");

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

When you stop an instance, it is 'deleted'. As such there's nothing to be charged for. If you have an Elastic IP or EBS, then you'll be charged for those - but nothing related to the instance itself.

Postgres FOR LOOP

I find it more convenient to make a connection using a procedural programming language (like Python) and do these types of queries.

import psycopg2
connection_psql = psycopg2.connect( user="admin_user"
                                  , password="***"
                                  , port="5432"
                                  , database="myDB"
                                  , host="[ENDPOINT]")
cursor_psql = connection_psql.cursor()

myList = [...]
for item in myList:
  cursor_psql.execute('''
    -- The query goes here
  ''')

connection_psql.commit()
cursor_psql.close()

How do I clone a range of array elements to a new array?

This is the optimal way, I found, to do this:

private void GetSubArrayThroughArraySegment() {
  int[] array = { 10, 20, 30 };
  ArraySegment<int> segment = new ArraySegment<int>(array,  1, 2);
  Console.WriteLine("-- Array --");
  int[] original = segment.Array;
  foreach (int value in original)
  {
    Console.WriteLine(value);
  }
  Console.WriteLine("-- Offset --");
  Console.WriteLine(segment.Offset);
  Console.WriteLine("-- Count --");
  Console.WriteLine(segment.Count);

  Console.WriteLine("-- Range --");
  for (int i = segment.Offset; i <= segment.Count; i++)
  {
    Console.WriteLine(segment.Array[i]);
  }
}

Hope It Helps!

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

How to make Regular expression into non-greedy?

I believe it would be like this

takedata.match(/(\[.+\])/g);

the g at the end means global, so it doesn't stop at the first match.

Storing data into list with class

You need to create an instance of the class to add:

lstemail.Add(new EmailData
                 {
                     FirstName = "JOhn",
                     LastName = "Smith",
                     Location = "Los Angeles"
                 });

See How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)


Alternatively you could declare a constructor for you EmailData object and use that to create the instance.

HTML5 Pre-resize images before uploading

Typescript

async resizeImg(file: Blob): Promise<Blob> {
    let img = document.createElement("img");
    img.src = await new Promise<any>(resolve => {
        let reader = new FileReader();
        reader.onload = (e: any) => resolve(e.target.result);
        reader.readAsDataURL(file);
    });
    await new Promise(resolve => img.onload = resolve)
    let canvas = document.createElement("canvas");
    let ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    let MAX_WIDTH = 1000;
    let MAX_HEIGHT = 1000;
    let width = img.naturalWidth;
    let height = img.naturalHeight;
    if (width > height) {
        if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
        }
    } else {
        if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
        }
    }
    canvas.width = width;
    canvas.height = height;
    ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0, width, height);
    let result = await new Promise<Blob>(resolve => { canvas.toBlob(resolve, 'image/jpeg', 0.95); });
    return result;
}

How to check if a view controller is presented modally or pushed on a navigation stack?

self.navigationController != nil would mean it's in a navigation stack.

Error while inserting date - Incorrect date value:

You can use "DATE" as a data type while you are creating the table. In this way, you can avoid the above error. Eg:

CREATE TABLE Employee (birth_date DATE);
INSERT INTO Employee VALUES('1967-11-17');

java.security.AccessControlException: Access denied (java.io.FilePermission

Just document it here on Windows you need to escape the \ character:

"e:\\directory\\-"

Test if a string contains a word in PHP?

Use strpos. If the string is not found it returns false, otherwise something that is not false. Be sure to use a type-safe comparison (===) as 0 may be returned and it is a falsy value:

if (strpos($string, $substring) === false) {
    // substring is not found in string
}

if (strpos($string, $substring2) !== false) {
    // substring2 is found in string
}

Find substring in the string in TWIG

Just searched for the docs, and found this:

Containment Operator: The in operator performs containment test. It returns true if the left operand is contained in the right:

{# returns true #}

{{ 1 in [1, 2, 3] }}

{{ 'cd' in 'abcde' }}