Programs & Examples On #Nsblockoperation

The NSBlockOperation class is a concrete subclass of NSOperation that manages the concurrent execution of one or more blocks. You can use this object to execute several blocks at once without having to create separate operation objects for each.

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

Get the cell value of a GridView row

I had the same problem as yours. I found that when i use the BoundField tag in GridView to show my data. The row.Cells[1].Text is working in:

GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";

But when i use TemplateField tag to show data like this:

 <asp:TemplateField HeaderText="??">
    <ItemTemplate>
    <asp:Label ID="Part_No" runat="server" Text='<%# Eval("Part_No")%>' ></asp:Label>
    </ItemTemplate>
    <HeaderStyle CssClass="bhead" />
    <ItemStyle CssClass="bbody" />
    </asp:TemplateField>

The row.Cells[1].Text just return null. I got stuck in this problem for a long time. I figur out recently and i want to share with someone who have the same problem my solution. Please feel free to edit this post and/or correct me.

My Solution:

Label lbCod = GridView1.Rows["AnyValidIndex"].Cells["AnyValidIndex"].Controls["AnyValidIndex"] as Label;

I use Controls attribute to find the Label control which i use to show data, and you can find yours. When you find it and convert to the correct type object than you can extract text and so on. Ex:

string showText = lbCod.Text;

Reference: reference

DBNull if statement

At first use ExecuteScalar

 objConn = new SqlConnection(strConnection);
 objConn.Open();
 objCmd = new SqlCommand(strSQL, objConn);
 object result = cmd.ExecuteScalar();
 if(result == null)
     strLevel = "";
 else 
     strLevel = result.ToString();

try/catch with InputMismatchException creates infinite loop

@Limp, your answer is right, just use .nextLine() while reading the input. Sample code:

    do {
        try {
            System.out.println("Enter first num: ");
            n1 = Integer.parseInt(input.nextLine());
            System.out.println("Enter second num: ");
            n2 = Integer.parseInt(input.nextLine());
            nQuotient = n1 / n2;
            bError = false;
        } catch (Exception e) {
            System.out.println("Error!");
        }
    } while (bError);

    System.out.printf("%d/%d = %d", n1, n2, nQuotient);

Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread. Java Homework user input issue

Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

Hiding the scroll bar on an HTML page

I believe you can manipulate it with the overflow CSS attribute, but they have limited browser support. One source said it was Internet Explorer 5 (and later), Firefox 1.5 (and later), and Safari 3 (and later) - maybe enough for your purposes.

Scrolling, Scrolling, Scrolling has a good discussion.

How do I install a Python package with a .whl file?

I would be suggesting you the exact way how to install .whl file. Initially I faced many issues but then I solved it, Here is my trick to install .whl files.

Follow The Steps properly in order to get a module imported

  1. Make sure your .whl file is kept in the python 2.7/3.6/3.7/.. folder. Initially when you download the .whl file the file is kept in downloaded folder, my suggestion is to change the folder. It makes it easier to install the file.
  2. Open command prompt and open the folder where you have kept the file by entering

cd c:\python 3.7

3.Now, enter the command written below

>py -3.7(version name) -m pip install (file name).whl
  1. Click enter and make sure you enter the version you are currently using with correct file name.

  2. Once you press enter, wait for few minutes and the file will be installed and you will be able to import the particular module.

  3. In order to check if the module is installed successfully, import the module in idle and check it.

Thank you:)

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I upgraded from Newtonsoft.Json 11.0.1 to 12.0.2. Opening the project file in Notepad++ I discovered both

<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
      <HintPath>..\packages\Newtonsoft.Json.12.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
    </Reference>

and

<ItemGroup>
    <Reference Include="Newtonsoft.Json">
      <HintPath>..\packages\Newtonsoft.Json.11.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
    </Reference>
  </ItemGroup>

I deleted the ItemGroup wrapping the reference with the hint path to version 11.0.1.

These issues can be insanely frustrating to find. What's more, developers often follow the same steps as previous project setups. The prior setups didn't encounter the issue. For whatever reason the project file occasionally is updated incorrectly.

I desperately wish Microsoft would fix these visual studio DLL hell issues from popping up. It happens far too often and causing progress to screech to a halt until it is fixed, often by trial and error.

How to detect online/offline event cross-browser?

Please find the require.js module that I wrote for Offline.

define(['offline'], function (Offline) {
    //Tested with Chrome and IE11 Latest Versions as of 20140412
    //Offline.js - http://github.hubspot.com/offline/ 
    //Offline.js is a library to automatically alert your users 
    //when they've lost internet connectivity, like Gmail.
    //It captures AJAX requests which were made while the connection 
    //was down, and remakes them when it's back up, so your app 
    //reacts perfectly.

    //It has a number of beautiful themes and requires no configuration.
    //Object that will be exposed to the outside world. (Revealing Module Pattern)

    var OfflineDetector = {};

    //Flag indicating current network status.
    var isOffline = false;

    //Configuration Options for Offline.js
    Offline.options = {
        checks: {
            xhr: {
                //By default Offline.js queries favicon.ico.
                //Change this to hit a service that simply returns a 204.
                url: 'favicon.ico'
            }
        },

        checkOnLoad: true,
        interceptRequests: true,
        reconnect: true,
        requests: true,
        game: false
    };

    //Offline.js raises the 'up' event when it is able to reach
    //the server indicating that connection is up.
    Offline.on('up', function () {
        isOffline = false;
    });

    //Offline.js raises the 'down' event when it is unable to reach
    //the server indicating that connection is down.
    Offline.on('down', function () {
        isOffline = true;
    });

    //Expose Offline.js instance for outside world!
    OfflineDetector.Offline = Offline;

    //OfflineDetector.isOffline() method returns the current status.
    OfflineDetector.isOffline = function () {
        return isOffline;
    };

    //start() method contains functionality to repeatedly
    //invoke check() method of Offline.js.
    //This repeated call helps in detecting the status.
    OfflineDetector.start = function () {
        var checkOfflineStatus = function () {
            Offline.check();
        };
        setInterval(checkOfflineStatus, 3000);
    };

    //Start OfflineDetector
    OfflineDetector.start();
    return OfflineDetector;
});

Please read this blog post and let me know your thoughts. http://zen-and-art-of-programming.blogspot.com/2014/04/html-5-offline-application-development.html It contains a code sample using offline.js to detect when the client is offline.

m2e error in MavenArchiver.getManifest()

I encountered the same issue after updating the maven-jar-plugin to its latest version (at the time of writing), 3.0.2.
Eclipse 4.5.2 started flagging the pom.xml file with the org.apache.maven.archiver.MavenArchiver.getManifest error and a Maven > Update Project.. would not fix it.

Easy solution: downgrade to 2.6 version
Indeed a possible solution is to get back to version 2.6, a further update of the project would then remove any error. However, that's not the ideal scenario and a better solution is possible: update the m2e extensions (Eclipse Maven integration).

Better solution: update Eclipse m2e extensions
From Help > Install New Software.., add a new repository (via the Add.. option), pointing to the following URL:

  • https://repo1.maven.org/maven2/.m2e/connectors/m2eclipse-mavenarchiver/0.17.2/N/LATEST/

Then follow the update wizard as usual. Eclipse would then require a restart. Afterwards, a further Update Project.. on the concerned Maven project would remove any error and your Maven build could then enjoy the benefit of the latest maven-jar-plugin version.


Additonal notes
The reason for this issue is that from version 3.0.0 on, the concerned component, the maven-archiver and the related plexus-archiver has been upgraded to newer versions, breaking internal usages (via reflections) of the m2e integration in Eclipse. The only solution is then to properly update Eclipse, as described above.
Also note: while Eclipse would initially report errors, the Maven build (e.g. from command line) would keep on working perfectly, this issue is only related to the Eclipse-Maven integration, that is, to the IDE.

How to pass parameters to a Script tag?

Another way is to use meta tags. Whatever data is supposed to be passed to your JavaScript can be assigned like this:

<meta name="yourdata" content="whatever" />
<meta name="moredata" content="more of this" />

The data can then be pulled from the meta tags like this (best done in a DOMContentLoaded event handler):

var data1 = document.getElementsByName('yourdata')[0].content;
var data2 = document.getElementsByName('moredata')[0].content;

Absolutely no hassle with jQuery or the likes, no hacks and workarounds necessary, and works with any HTML version that supports meta tags...

Javascript split regex question

or just use for date strings 2015-05-20 or 2015.05.20

date.split(/\.|-/);

codeigniter, result() vs. result_array()

result() returns Object type data. . . . result_array() returns Associative Array type data.

JavaScript: clone a function

Here is an updated answer

var newFunc = oldFunc.bind({}); //clones the function with '{}' acting as it's new 'this' parameter

However .bind is a modern ( >=iE9 ) feature of JavaScript (with a compatibility workaround from MDN)

Notes

  1. It does not clone the function object additional attached properties, including the prototype property. Credit to @jchook

  2. The new function this variable is stuck with the argument given on bind(), even on new function apply() calls. Credit to @Kevin

function oldFunc() {
  console.log(this.msg);
}
var newFunc = oldFunc.bind({ msg: "You shall not pass!" }); // this object is binded
newFunc.apply({ msg: "hello world" }); //logs "You shall not pass!" instead
  1. Bound function object, instanceof treats newFunc/oldFunc as the same. Credit to @Christopher
(new newFunc()) instanceof oldFunc; //gives true
(new oldFunc()) instanceof newFunc; //gives true as well
newFunc == oldFunc; //gives false however

Mock MVC - Add Request Parameter to test

When i analyzed your code. I have also faced the same problem but my problem is if i give value for both first and last name means it is working fine. but when i give only one value means it says 400. anyway use the .andDo(print()) method to find out the error

public void testGetUserByName() throws Exception {
    String firstName = "Jack";
    String lastName = "s";       
    this.userClientObject = client.createClient();
    mockMvc.perform(get("/byName")
            .sessionAttr("userClientObject", this.userClientObject)
            .param("firstName", firstName)
            .param("lastName", lastName)               
    ).andDo(print())
     .andExpect(status().isOk())
            .andExpect(content().contentType("application/json"))
            .andExpect(jsonPath("$[0].id").exists())
            .andExpect(jsonPath("$[0].fn").value("Marge"));
}

If your problem is org.springframework.web.bind.missingservletrequestparameterexception you have to change your code to

@RequestMapping(value = "/byName", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public
    @ResponseBody
    String getUserByName(
        @RequestParam( value="firstName",required = false) String firstName,
        @RequestParam(value="lastName",required = false) String lastName, 
        @ModelAttribute("userClientObject") UserClient userClient)
    {

        return client.getUserByName(userClient, firstName, lastName);
    }

How to give a time delay of less than one second in excel vba?

Everyone tries Application.Wait, but that's not really reliable. If you ask it to wait for less than a second, you'll get anything between 0 and 1, but closer to 10 seconds. Here's a demonstration using a wait of 0.5 seconds:

Sub TestWait()
  Dim i As Long
  For i = 1 To 5
    Dim t As Double
    t = Timer
    Application.Wait Now + TimeValue("0:00:00") / 2
    Debug.Print Timer - t
  Next
End Sub

Here's the output, an average of 0.0015625 seconds:

0
0
0
0.0078125
0

Admittedly, Timer may not be the ideal way to measure these events, but you get the idea.

The Timer approach is better:

Sub TestTimer()
  Dim i As Long
  For i = 1 To 5
    Dim t As Double
    t = Timer
    Do Until Timer - t >= 0.5
      DoEvents
    Loop
    Debug.Print Timer - t
  Next
End Sub

And the results average is very close to 0.5 seconds:

0.5
0.5
0.5
0.5
0.5

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

One command to convert date time to Unix format and then to string

    DateTime.strptime(Time.now.utc.to_i.to_s,'%s').strftime("%d %m %y")

    Time.now.utc.to_i #Converts time from Unix format
    DateTime.strptime(Time.now.utc.to_i.to_s,'%s') #Converts date and time from unix format to DateTime

finally strftime is used to format date

Example:

    irb(main):034:0> DateTime.strptime("1410321600",'%s').strftime("%d %m %y")
    "10 09 14"

How to set TextView textStyle such as bold, italic

Try this to set on TextView for bold or italic

textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
textView.setTypeface(textView.getTypeface(), Typeface.ITALIC);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC);

How can I issue a single command from the command line through sql plus?

@find /v "@" < %0 | sqlplus -s scott/tiger@orcl & goto :eof

select sysdate from dual;

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

May be it helps some one, On Android i had same issue but i figured it out by using setTimeout inside document.ready so it worked for me secondly you have to increase the timeout just incase if user allow his location after few seconds, so i kept it to 60000 mili seconds (1 minute) allowing my success function to call if user click on allow button within 1 minute.

Access 2010 VBA query a table and iterate through results

DAO is native to Access and by far the best for general use. ADO has its place, but it is unlikely that this is it.

 Dim rs As DAO.Recordset
 Dim db As Database
 Dim strSQL as String

 Set db=CurrentDB

 strSQL = "select * from table where some condition"

 Set rs = db.OpenRecordset(strSQL)

 Do While Not rs.EOF

    rs.Edit
    rs!SomeField = "Abc"
    rs!OtherField = 2
    rs!ADate = Date()
    rs.Update

    rs.MoveNext
Loop

How can I do an OrderBy with a dynamic string parameter?

Another solution from codeConcussion (https://stackoverflow.com/a/7265394/2793768)

var param = "Address";    
var pi = typeof(Student).GetProperty(param);    
var orderByAddress = items.OrderBy(x => pi.GetValue(x, null));

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

First you should learn about loops, in this case most suitable is for loop. For instance let's initialize whole table with increasing values starting with 0:

final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
    array[i] = i;
}

Now you can modify it to initialize your table with values as per your assignment. But what happen if you replace condition i < SIZE with i < 11? Well, you will get IndexOutOfBoundException, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.

In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.

What is the simplest way to swap each pair of adjoining chars in a string with Python?

One more way:

>>> s='123456'
>>> ''.join([''.join(el) for el in zip(s[1::2], s[0::2])])
'214365'

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

FileNotFoundException..Classpath resource not found in spring?

Looking at your classpath you exclude src/main/resources and src/test/resources:

    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
    <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>

Is there a reason for it? Try not to exclude a classpath to spring-config.xml :)

Convert DateTime to long and also the other way around

   long dateTime = DateTime.Now.Ticks;
   Console.WriteLine(dateTime);
   Console.WriteLine(new DateTime(dateTime));
   Console.ReadKey();

Check if enum exists in Java

One of my favorite lib: Apache Commons.

The EnumUtils can do that easily.

Following an example to validate an Enum with that library:

public enum MyEnum {
    DIV("div"), DEPT("dept"), CLASS("class");

    private final String val;

    MyEnum(String val) {
    this.val = val;
    }

    public String getVal() {
    return val;
    }
}


MyEnum strTypeEnum = null;

// test if String str is compatible with the enum 
// e.g. if you pass str = "div", it will return false. If you pass "DIV", it will return true.
if( EnumUtils.isValidEnum(MyEnum.class, str) ){
    strTypeEnum = MyEnum.valueOf(str);
}

How to pull remote branch from somebody else's repo

If the forked repo is protected so you can't push directly into it, and your goal is to make changes to their foo, then you need to get their branch foo into your repo like so:

git remote add protected_repo https://github.com/theirusername/their_repo.git
git fetch protected_repo 
git checkout --no-track protected_repo/foo

Now you have a local copy of foo with no upstream associated to it. You can commit changes to it (or not) and then push your foo to your own remote repo.

git push --set-upstream origin foo

Now foo is in your repo on GitHub and your local foo is tracking it. If they continue to make changes to foo you can fetch theirs and merge into your foo.

git checkout foo 
git fetch protected_repo
git merge protected_repo/foo

AngularJS: How to clear query parameters in the URL?

If you are using routes parameters just clear $routeParams

$routeParams= null;

Checking if any elements in one list are in another

Your original approach can work with a list comprehension:

def listCompare():
  list1 = [1, 2, 3, 4, 5]
  list2 = [5, 6, 7, 8, 9]
  if [item for item in list1 if item in list2]:
    print("Number was found")
  else:
    print("Number not in list")

How can I change the thickness of my <hr> tag

I suggest to use construction like

<style>
  .hr { height:0; border-top:1px solid _anycolor_; }
  .hr hr { display:none }
</style>

<div class="hr"><hr /></div>

How to log as much information as possible for a Java Exception?

It should be quite simple if you are using LogBack or SLF4J. I do it as below

//imports
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//Initialize logger
Logger logger = LoggerFactory.getLogger(<classname>.class);
try {
   //try something
} catch(Exception e){
   //Actual logging of error
   logger.error("some message", e);
}

Submit form with Enter key without submit button?

@JayGuilford's answer is a good one, but if you don't want a JS dependency, you could use a submit element and simply hide it using display: none;.

Changing file permission in Python

Just add 0 before the permission number:
For example - we want to give all permissions - 777
Syntax: os.chmod("file_name" , permission)

import os
os.chmod("file_name" , 0777)

Python version 3.7 does not support this syntax. It requires '0o' prefix for octal literals - this is the comment I have got in PyCharm

So for python 3.7, it will be

import os
os.chmod("file_name" , 0o777)

How to center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.

Now, add the style to the div class and use the text-align property with center as its value.

See the below example.

<style>
.myDivElement{
    text-align:center;
}
.myDivElement ul li{
   display:inline;

 }
</style>
<div class="myDivElement">
<ul>
    <li>Home</li>
    <li>About</li>
    <li>Gallery</li>
    <li>Contact</li>
</ul>
</div>

Here is the reference website Center Align Unordered List

How do I implement JQuery.noConflict() ?

You simply assign a custom variable for JQuery to use instead of its default $. JQuery then wraps itself in a new function scope so $ no longer has a namespace conflict.

<script type="text/javascript">
    $jQuery = $.noConflict();
    // Other library code here which uses '$'
    $jQuery(function(){ /* dom ready */ }
</script>

Load local javascript file in chrome for testing?

The easiest workaround I have found is to use Firefox. Not only does it work with no extra steps (drag and drop - no muss no fuss), but blackboxing works better than Chrome.

PHP - Copy image to my server direct from URL

$url="http://www.google.co.in/intl/en_com/images/srpr/logo1w.png";
$contents=file_get_contents($url);
$save_path="/path/to/the/dir/and/image.jpg";
file_put_contents($save_path,$contents);

you must have allow_url_fopen set to on

jQuery - how to write 'if not equal to' (opposite of ==)

!=

For example,

if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])

JFrame in full screen Java

you can simply do like this -

public void FullScreen() {
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) {
            final View v = this.activity.getWindow().getDecorView();
            v.setSystemUiVisibility(8);
        }
        else if (Build.VERSION.SDK_INT >= 19) {
            final View decorView = this.activity.getWindow().getDecorView();
            final int uiOptions = 4102;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

How to use ArrayList's get() method

Here is the official documentation of ArrayList.get().

Anyway it is very simple, for example

ArrayList list = new ArrayList();
list.add("1");
list.add("2");
list.add("3");
String str = (String) list.get(0); // here you get "1" in str

Getting data posted in between two dates

$query = $this->db
              ->get_where('orders',array('order_date <='=>$first_date,'order_date >='=>$second_date))
              ->result_array();

what is the use of $this->uri->segment(3) in codeigniter pagination

In your code $this->uri->segment(3) refers to the pagination offset which you use in your query. According to your $config['base_url'] = base_url().'index.php/papplicant/viewdeletedrecords/' ;, $this->uri->segment(3) i.e segment 3 refers to the offset. The first segment is the controller, second is the method, there after comes the parameters sent to the controllers as segments.

Identify duplicates in a List

You can use something like this:

List<Integer> newList = new ArrayList<Integer>();
for(int i : yourOldList)
{
    yourOldList.remove(i);
    if(yourOldList.contains(i) && !newList.contains(i)) newList.add(i);
}

AngularJS resource promise

If you're looking to get promise in resource call, you should use

Regions.query().$q.then(function(){ .... })

Update : the promise syntax is changed in current versions which reads

Regions.query().$promise.then(function(){ ..... })

Those who have downvoted don't know what it was and who first added this promise to resource object. I used this feature in late 2012 - yes 2012.

Difference between IISRESET and IIS Stop-Start command

Take IISReset as a suite of commands that helps you manage IIS start / stop etc.

Which means you need to specify option (/switch) what you want to do to carry any operation.

Default behavior OR default switch is /restart with iisreset so you do not need to run command twice with /start and /stop.

Hope this clarifies your question. For reference the output of iisreset /? is:

IISRESET.EXE (c) Microsoft Corp. 1998-2005

Usage:
iisreset [computername]

    /RESTART            Stop and then restart all Internet services.
    /START              Start all Internet services.
    /STOP               Stop all Internet services.
    /REBOOT             Reboot the computer.
    /REBOOTONERROR      Reboot the computer if an error occurs when starting,
                        stopping, or restarting Internet services.
    /NOFORCE            Do not forcefully terminate Internet services if
                        attempting to stop them gracefully fails.
    /TIMEOUT:val        Specify the timeout value ( in seconds ) to wait for
                        a successful stop of Internet services. On expiration
                        of this timeout the computer can be rebooted if
                        the /REBOOTONERROR parameter is specified.
                        The default value is 20s for restart, 60s for stop,
                        and 0s for reboot.
    /STATUS             Display the status of all Internet services.
    /ENABLE             Enable restarting of Internet Services
                        on the local system.
    /DISABLE            Disable restarting of Internet Services
                        on the local system.

AngularJS app.run() documentation?

Here's the calling order:

  1. app.config()
  2. app.run()
  3. directive's compile functions (if they are found in the dom)
  4. app.controller()
  5. directive's link functions (again, if found)

Here's a simple demo where you can watch each one executing (and experiment if you'd like).

From Angular's module docs:

Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the services have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.

One situation where run blocks are used is during authentications.

How to resume Fragment from BackStack if exists

Step 1: Implement an interface with your activity class

public class AuthenticatedMainActivity extends Activity implements FragmentManager.OnBackStackChangedListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        .............
        FragmentManager fragmentManager = getFragmentManager();           
        fragmentManager.beginTransaction().add(R.id.frame_container,fragment, "First").addToBackStack(null).commit();
    }

    private void switchFragment(Fragment fragment){            
      FragmentManager fragmentManager = getFragmentManager();
      fragmentManager.beginTransaction()
        .replace(R.id.frame_container, fragment).addToBackStack("Tag").commit();
    }

    @Override
    public void onBackStackChanged() {
    FragmentManager fragmentManager = getFragmentManager();

    System.out.println("@Class: SummaryUser : onBackStackChanged " 
            + fragmentManager.getBackStackEntryCount());

    int count = fragmentManager.getBackStackEntryCount();

    // when a fragment come from another the status will be zero
    if(count == 0){

        System.out.println("again loading user data");

        // reload the page if user saved the profile data

        if(!objPublicDelegate.checkNetworkStatus()){

            objPublicDelegate.showAlertDialog("Warning"
                    , "Please check your internet connection");

        }else {

            objLoadingDialog.show("Refreshing data..."); 

            mNetworkMaster.runUserSummaryAsync();
        }

        // IMPORTANT: remove the current fragment from stack to avoid new instance
        fragmentManager.removeOnBackStackChangedListener(this);

    }// end if
   }       
}

Step 2: When you call the another fragment add this method:

String backStateName = this.getClass().getName();

FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this); 

Fragment fragmentGraph = new GraphFragment();
Bundle bundle = new Bundle();
bundle.putString("graphTag",  view.getTag().toString());
fragmentGraph.setArguments(bundle);

fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragmentGraph)
.addToBackStack(backStateName)
.commit();

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

Python "string_escape" vs "unicode_escape"

Within the range 0 = c < 128, yes the ' is the only difference for CPython 2.6.

>>> set(unichr(c).encode('unicode_escape') for c in range(128)) - set(chr(c).encode('string_escape') for c in range(128))
set(["'"])

Outside of this range the two types are not exchangeable.

>>> '\x80'.encode('string_escape')
'\\x80'
>>> '\x80'.encode('unicode_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can’t decode byte 0x80 in position 0: ordinal not in range(128)

>>> u'1'.encode('unicode_escape')
'1'
>>> u'1'.encode('string_escape')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: escape_encode() argument 1 must be str, not unicode

On Python 3.x, the string_escape encoding no longer exists, since str can only store Unicode.

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I too had a similar type of problem . The solution is simple . just dont try to enter NULL or None value in values or u might have to use Something like this
dic.update([(key,value)])

What is a Y-combinator?

If you're ready for a long read, Mike Vanier has a great explanation. Long story short, it allows you to implement recursion in a language that doesn't necessarily support it natively.

GROUP_CONCAT ORDER BY

Try

SELECT li.clientid, group_concat(li.views ORDER BY li.views) AS views,
       group_concat(li.percentage ORDER BY li.percentage) 
FROM table_views li 
GROUP BY client_id

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat

Programmatically extract contents of InstallShield setup.exe

http://www.compdigitec.com/labs/files/isxunpack.exe

Usage: isxunpack.exe yourinstallshield.exe

It will extract in the same folder.

JavaScript: What are .extend and .prototype used for?

  • .extends() create a class which is a child of another class.
    behind the scenes Child.prototype.__proto__ sets its value to Parent.prototype
    so methods are inherited.
  • .prototype inherit features from one to another.
  • .__proto__ is a getter/setter for Prototype.

OSError [Errno 22] invalid argument when use open() in Python

In my case,the problem exists beacause I have not set permission for drive "C:\" and when I change my path to other drive like "F:\" my problem resolved.

How to match, but not capture, part of a regex?

I have modified one of the answers (by @op1ekun):

123-(apple(?=-)|banana(?=-)|(?!-))-?456

The reason is that the answer from @op1ekun also matches "123-apple456", without the hyphen after apple.

How to bind Close command to a button

All it takes is a bit of XAML...

<Window x:Class="WCSamples.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.CommandBindings>
        <CommandBinding Command="ApplicationCommands.Close"
                        Executed="CloseCommandHandler"/>
    </Window.CommandBindings>
    <StackPanel Name="MainStackPanel">
        <Button Command="ApplicationCommands.Close" 
                Content="Close Window" />
    </StackPanel>
</Window>

And a bit of C#...

private void CloseCommandHandler(object sender, ExecutedRoutedEventArgs e)
{
    this.Close();
}

(adapted from this MSDN article)

SQLite string contains other string query

Using LIKE:

SELECT *
  FROM TABLE
 WHERE column LIKE '%cats%'  --case-insensitive

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

Remove the onchange event from the HTML Markup and bind it in your document ready event

<select  name="a[b]" >
     <option value='Choice 1'>Choice 1</option>
     <option value='Choice 2'>Choice 2</option>
</select>?

and Script

$(function(){    
    $("select[name='a[b]']").change(function(){
       alert($(this).val());        
    }); 
});

Working sample : http://jsfiddle.net/gLaR8/3/

Dynamically replace img src attribute with jQuery

You need to check out the attr method in the jQuery docs. You are misusing it. What you are doing within the if statements simply replaces all image tags src with the string specified in the 2nd parameter.

http://api.jquery.com/attr/

A better way to approach replacing a series of images source would be to loop through each and check it's source.

Example:

$('img').each(function () {
  var curSrc = $(this).attr('src');
  if ( curSrc === 'http://example.com/smith.gif' ) {
      $(this).attr('src', 'http://example.com/johnson.gif');
  }
  if ( curSrc === 'http://example.com/williams.gif' ) {
      $(this).attr('src', 'http://example.com/brown.gif');
  }
});

How to upload file to server with HTTP POST multipart/form-data?

For people searching for 403 forbidden issue while trying to upload in multipart form the below might help as there is a case depending on the server configuration that you will get MULTIPART_STRICT_ERROR "!@eq 0" due to incorrect MultipartFormDataContent headers. Please note that both imagetag/filename variables include quotations (\") eg filename="\"myfile.png\"" .

    MultipartFormDataContent form = new MultipartFormDataContent();
    ByteArrayContent imageContent = new ByteArrayContent(fileBytes, 0, fileBytes.Length);
    imageContent.Headers.TryAddWithoutValidation("Content-Disposition", "form-data; name="+imagetag+"; filename="+filename);
    imageContent.Headers.TryAddWithoutValidation("Content-Type", "image / png");
    form.Add(imageContent, imagetag, filename);

C#: Waiting for all threads to complete

I was tying to figure out how to do this but i could not get any answers from google. I know this is an old thread but here was my solution:

Use the following class:

class ThreadWaiter
    {
        private int _numThreads = 0;
        private int _spinTime;

        public ThreadWaiter(int SpinTime)
        {
            this._spinTime = SpinTime;
        }

        public void AddThreads(int numThreads)
        {
            _numThreads += numThreads;
        }

        public void RemoveThread()
        {
            if (_numThreads > 0)
            {
                _numThreads--;
            }
        }

        public void Wait()
        {
            while (_numThreads != 0)
            {
                System.Threading.Thread.Sleep(_spinTime);
            }
        }
    }
  1. Call Addthreads(int numThreads) before executing a thread(s).
  2. Call RemoveThread() after each one has completed.
  3. Use Wait() at the point that you want to wait for all the threads to complete before continuing

Mean Squared Error in Numpy?

This isn't part of numpy, but it will work with numpy.ndarray objects. A numpy.matrix can be converted to a numpy.ndarray and a numpy.ndarray can be converted to a numpy.matrix.

from sklearn.metrics import mean_squared_error
mse = mean_squared_error(A, B)

See Scikit Learn mean_squared_error for documentation on how to control axis.

Extract the filename from a path

If you are ok with including the extension this should do what you want.

$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf

How to get the 'height' of the screen using jquery

$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

As documented here: http://api.jquery.com/height/

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

Make Bootstrap 3 Tabs Responsive

Pure CSS only for nav tabs, very simple for small screens:

@media (max-width: 767px) {
     .nav-tabs {
         min-width: 100%;
         display: inline-grid;
     }
}

Chart.js - Formatting Y axis

I had the same problem, I think in Chart.js 2.x.x the approach is slightly different like below.

ticks: {
    callback: function(label, index, labels) {
        return label/1000+'k';
    }
}

More in details

var options = {
    scales: {
        yAxes: [
            {
                ticks: {
                    callback: function(label, index, labels) {
                        return label/1000+'k';
                    }
                },
                scaleLabel: {
                    display: true,
                    labelString: '1k = 1000'
                }
            }
        ]
    }
}

convert base64 to image in javascript/jquery

This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.

It also answers the original question on how to get an image (file) from the Base 64 data:

The important part is the Base 64 - Binary conversion:

function base64toBlob(base64Data, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    return new Blob(byteArrays, { type: contentType });
}

Slicing is required to avoid out of memory errors.

Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.

Here's the code to write the file to the device's local storage with Cordova / Android:

...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {

                    // Setup filename and assume a jpg file
                    var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
                    dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
                        // attachment.document holds the base 64 data at this moment
                        var binary = base64toBlob(attachment.document, attachment.mimetype);
                        writeFile(fileEntry, binary).then(function() {
                            // Store file url for later reference, base 64 data is no longer required
                            attachment.document = fileEntry.nativeURL;

                        }, function(error) {
                            WL.Logger.error("Error writing local file: " + error);
                            reject(error.code);
                        });

                    }, function(errorCreateFile) {
                        WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
                        reject(errorCreateFile.code);
                    });

                }, function(errorCreateFS) {
                    WL.Logger.error("Error getting filesystem: " + errorCreateFS);
                    reject(errorCreateFS.code);
                });
...

Writing the file itself:

function writeFile(fileEntry, dataObj) {
    return $q(function(resolve, reject) {
        // Create a FileWriter object for our FileEntry (log.txt).
        fileEntry.createWriter(function(fileWriter) {

            fileWriter.onwriteend = function() {
                WL.Logger.debug(LOG_PREFIX + "Successful file write...");
                resolve();
            };

            fileWriter.onerror = function(e) {
                WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
                reject(e);
            };

            // If data object is not passed in,
            // create a new Blob instead.
            if (!dataObj) {
                dataObj = new Blob(['missing data'], { type: 'text/plain' });
            }

            fileWriter.write(dataObj);
        });
    })
}

I am using the latest Cordova (6.5.0) and Plugins versions:

I hope this sets everyone here in the right direction.

Where is the correct location to put Log4j.properties in an Eclipse project?

The best way is to create special source folder named resources and use it for all resource including log4j.properties. So, just put it there.

On the Java Resources folder that was automatically created by the Dynamic Web Project, right click and add a new Source Folder and name it 'resources'. Files here will then be exported to the war file to the classes directory

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I believe I ran exactly into the same issue. After countless hours of fighting with the JSON, the JavaScript and the Server, I found the culprit: In my case I had a Date object in the DTO, this Date object was converted to a String so we could show it in the view with the format: HH:mm.

When JSON information was being sent back, this Date String object had to be converted back into a full Date Object, therefore we also need a method to set it in the DTO. The big BUT is you cannot have 2 methods with the same name (Overload) in the DTO even if they have different type of parameter (String vs Date) because this will give you also the 415 Unsupported Media type error.

This was my controller method

  @RequestMapping(value = "/alarmdownload/update", produces = "application/json", method = RequestMethod.POST)
  public @ResponseBody
  StatusResponse update(@RequestBody AlarmDownloadDTO[] rowList) {
    System.out.println("hola");
    return new StatusResponse();
  }

This was my DTO example (id get/set and preAlarm get Methods are not included for code shortness):

@JsonIgnoreProperties(ignoreUnknown = true)
public class AlarmDownloadDTO implements Serializable {

  private static final SimpleDateFormat formatHHmm = new SimpleDateFormat("HH:mm");

  private String id;
  private Date preAlarm;

  public void setPreAlarm(Date date) { 
    this.preAlarm == date;
  }
  public void setPreAlarm(String date) {    
    try {
      this.preAlarm = formatHHmm.parse(date);
    } catch (ParseException e) {
      this.preAlarm = null;
    } catch (NullPointerException e){
      this.preAlarm = null;
    }
  }
}

To make everything work you need to remove the method with Date type parameter. This error is very frustrating. Hope this can save someone hours of debugging.

fatal error LNK1104: cannot open file 'kernel32.lib'

I had a differnt problem on Windows 10 with Visual Studio 2017 but with the same effects. I think my problems came down to VS being installed onto a drive other than "C:\". I solved the problem by Reinstalling Windows 10 SDK

First I had to uninstall the Windows SDK (there were two versions installed). Then ran the executable. Once installed, ran visual studio and it worked fine.

Install opencv for Python 3.3

Yes support for Python 3 it is still not available in current version, but it will be available from version 3.0, (see this ticket). If you really want to have python 3 try using development version, you can download it from GitHub.

EDIT (18/07/2015): version 3.0 is now released and python 3 support is now officially available

HTML5 record audio to file

The code shown below is copyrighted to Matt Diamond and available for use under MIT license. The original files are here:

Save this files and use

_x000D_
_x000D_
(function(window){_x000D_
_x000D_
      var WORKER_PATH = 'recorderWorker.js';_x000D_
      var Recorder = function(source, cfg){_x000D_
        var config = cfg || {};_x000D_
        var bufferLen = config.bufferLen || 4096;_x000D_
        this.context = source.context;_x000D_
        this.node = this.context.createScriptProcessor(bufferLen, 2, 2);_x000D_
        var worker = new Worker(config.workerPath || WORKER_PATH);_x000D_
        worker.postMessage({_x000D_
          command: 'init',_x000D_
          config: {_x000D_
            sampleRate: this.context.sampleRate_x000D_
          }_x000D_
        });_x000D_
        var recording = false,_x000D_
          currCallback;_x000D_
_x000D_
        this.node.onaudioprocess = function(e){_x000D_
          if (!recording) return;_x000D_
          worker.postMessage({_x000D_
            command: 'record',_x000D_
            buffer: [_x000D_
              e.inputBuffer.getChannelData(0),_x000D_
              e.inputBuffer.getChannelData(1)_x000D_
            ]_x000D_
          });_x000D_
        }_x000D_
_x000D_
        this.configure = function(cfg){_x000D_
          for (var prop in cfg){_x000D_
            if (cfg.hasOwnProperty(prop)){_x000D_
              config[prop] = cfg[prop];_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
_x000D_
        this.record = function(){_x000D_
       _x000D_
          recording = true;_x000D_
        }_x000D_
_x000D_
        this.stop = function(){_x000D_
        _x000D_
          recording = false;_x000D_
        }_x000D_
_x000D_
        this.clear = function(){_x000D_
          worker.postMessage({ command: 'clear' });_x000D_
        }_x000D_
_x000D_
        this.getBuffer = function(cb) {_x000D_
          currCallback = cb || config.callback;_x000D_
          worker.postMessage({ command: 'getBuffer' })_x000D_
        }_x000D_
_x000D_
        this.exportWAV = function(cb, type){_x000D_
          currCallback = cb || config.callback;_x000D_
          type = type || config.type || 'audio/wav';_x000D_
          if (!currCallback) throw new Error('Callback not set');_x000D_
          worker.postMessage({_x000D_
            command: 'exportWAV',_x000D_
            type: type_x000D_
          });_x000D_
        }_x000D_
_x000D_
        worker.onmessage = function(e){_x000D_
          var blob = e.data;_x000D_
          currCallback(blob);_x000D_
        }_x000D_
_x000D_
        source.connect(this.node);_x000D_
        this.node.connect(this.context.destination);    //this should not be necessary_x000D_
      };_x000D_
_x000D_
      Recorder.forceDownload = function(blob, filename){_x000D_
        var url = (window.URL || window.webkitURL).createObjectURL(blob);_x000D_
        var link = window.document.createElement('a');_x000D_
        link.href = url;_x000D_
        link.download = filename || 'output.wav';_x000D_
        var click = document.createEvent("Event");_x000D_
        click.initEvent("click", true, true);_x000D_
        link.dispatchEvent(click);_x000D_
      }_x000D_
_x000D_
      window.Recorder = Recorder;_x000D_
_x000D_
    })(window);_x000D_
_x000D_
    //ADDITIONAL JS recorderWorker.js_x000D_
    var recLength = 0,_x000D_
      recBuffersL = [],_x000D_
      recBuffersR = [],_x000D_
      sampleRate;_x000D_
    this.onmessage = function(e){_x000D_
      switch(e.data.command){_x000D_
        case 'init':_x000D_
          init(e.data.config);_x000D_
          break;_x000D_
        case 'record':_x000D_
          record(e.data.buffer);_x000D_
          break;_x000D_
        case 'exportWAV':_x000D_
          exportWAV(e.data.type);_x000D_
          break;_x000D_
        case 'getBuffer':_x000D_
          getBuffer();_x000D_
          break;_x000D_
        case 'clear':_x000D_
          clear();_x000D_
          break;_x000D_
      }_x000D_
    };_x000D_
_x000D_
    function init(config){_x000D_
      sampleRate = config.sampleRate;_x000D_
    }_x000D_
_x000D_
    function record(inputBuffer){_x000D_
_x000D_
      recBuffersL.push(inputBuffer[0]);_x000D_
      recBuffersR.push(inputBuffer[1]);_x000D_
      recLength += inputBuffer[0].length;_x000D_
    }_x000D_
_x000D_
    function exportWAV(type){_x000D_
      var bufferL = mergeBuffers(recBuffersL, recLength);_x000D_
      var bufferR = mergeBuffers(recBuffersR, recLength);_x000D_
      var interleaved = interleave(bufferL, bufferR);_x000D_
      var dataview = encodeWAV(interleaved);_x000D_
      var audioBlob = new Blob([dataview], { type: type });_x000D_
_x000D_
      this.postMessage(audioBlob);_x000D_
    }_x000D_
_x000D_
    function getBuffer() {_x000D_
      var buffers = [];_x000D_
      buffers.push( mergeBuffers(recBuffersL, recLength) );_x000D_
      buffers.push( mergeBuffers(recBuffersR, recLength) );_x000D_
      this.postMessage(buffers);_x000D_
    }_x000D_
_x000D_
    function clear(){_x000D_
      recLength = 0;_x000D_
      recBuffersL = [];_x000D_
      recBuffersR = [];_x000D_
    }_x000D_
_x000D_
    function mergeBuffers(recBuffers, recLength){_x000D_
      var result = new Float32Array(recLength);_x000D_
      var offset = 0;_x000D_
      for (var i = 0; i < recBuffers.length; i++){_x000D_
        result.set(recBuffers[i], offset);_x000D_
        offset += recBuffers[i].length;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function interleave(inputL, inputR){_x000D_
      var length = inputL.length + inputR.length;_x000D_
      var result = new Float32Array(length);_x000D_
_x000D_
      var index = 0,_x000D_
        inputIndex = 0;_x000D_
_x000D_
      while (index < length){_x000D_
        result[index++] = inputL[inputIndex];_x000D_
        result[index++] = inputR[inputIndex];_x000D_
        inputIndex++;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function floatTo16BitPCM(output, offset, input){_x000D_
      for (var i = 0; i < input.length; i++, offset+=2){_x000D_
        var s = Math.max(-1, Math.min(1, input[i]));_x000D_
        output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function writeString(view, offset, string){_x000D_
      for (var i = 0; i < string.length; i++){_x000D_
        view.setUint8(offset + i, string.charCodeAt(i));_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function encodeWAV(samples){_x000D_
      var buffer = new ArrayBuffer(44 + samples.length * 2);_x000D_
      var view = new DataView(buffer);_x000D_
_x000D_
      /* RIFF identifier */_x000D_
      writeString(view, 0, 'RIFF');_x000D_
      /* file length */_x000D_
      view.setUint32(4, 32 + samples.length * 2, true);_x000D_
      /* RIFF type */_x000D_
      writeString(view, 8, 'WAVE');_x000D_
      /* format chunk identifier */_x000D_
      writeString(view, 12, 'fmt ');_x000D_
      /* format chunk length */_x000D_
      view.setUint32(16, 16, true);_x000D_
      /* sample format (raw) */_x000D_
      view.setUint16(20, 1, true);_x000D_
      /* channel count */_x000D_
      view.setUint16(22, 2, true);_x000D_
      /* sample rate */_x000D_
      view.setUint32(24, sampleRate, true);_x000D_
      /* byte rate (sample rate * block align) */_x000D_
      view.setUint32(28, sampleRate * 4, true);_x000D_
      /* block align (channel count * bytes per sample) */_x000D_
      view.setUint16(32, 4, true);_x000D_
      /* bits per sample */_x000D_
      view.setUint16(34, 16, true);_x000D_
      /* data chunk identifier */_x000D_
      writeString(view, 36, 'data');_x000D_
      /* data chunk length */_x000D_
      view.setUint32(40, samples.length * 2, true);_x000D_
_x000D_
      floatTo16BitPCM(view, 44, samples);_x000D_
_x000D_
      return view;_x000D_
    }
_x000D_
<html>_x000D_
     <body>_x000D_
      <audio controls autoplay></audio>_x000D_
      <script type="text/javascript" src="recorder.js"> </script>_x000D_
                    <fieldset><legend>RECORD AUDIO</legend>_x000D_
      <input onclick="startRecording()" type="button" value="start recording" />_x000D_
      <input onclick="stopRecording()" type="button" value="stop recording and play" />_x000D_
                    </fieldset>_x000D_
      <script>_x000D_
       var onFail = function(e) {_x000D_
        console.log('Rejected!', e);_x000D_
       };_x000D_
_x000D_
       var onSuccess = function(s) {_x000D_
        var context = new webkitAudioContext();_x000D_
        var mediaStreamSource = context.createMediaStreamSource(s);_x000D_
        recorder = new Recorder(mediaStreamSource);_x000D_
        recorder.record();_x000D_
_x000D_
        // audio loopback_x000D_
        // mediaStreamSource.connect(context.destination);_x000D_
       }_x000D_
_x000D_
       window.URL = window.URL || window.webkitURL;_x000D_
       navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;_x000D_
_x000D_
       var recorder;_x000D_
       var audio = document.querySelector('audio');_x000D_
_x000D_
       function startRecording() {_x000D_
        if (navigator.getUserMedia) {_x000D_
         navigator.getUserMedia({audio: true}, onSuccess, onFail);_x000D_
        } else {_x000D_
         console.log('navigator.getUserMedia not present');_x000D_
        }_x000D_
       }_x000D_
_x000D_
       function stopRecording() {_x000D_
        recorder.stop();_x000D_
        recorder.exportWAV(function(s) {_x000D_
                                _x000D_
                                  audio.src = window.URL.createObjectURL(s);_x000D_
        });_x000D_
       }_x000D_
      </script>_x000D_
     </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

How to uncommit my last commit in Git

Be careful with that.

But you can use the rebase command

git rebase -i HEAD~2

A vi will open and all you have to do is delete the line with the commit. Also can read instructions that were shown in proper edition @ vi. A couple of things can be performed on this mode.

Convert array of JSON object strings to array of JS objects

If you have a JS array of JSON objects:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

See the speed tests for browser comparisons.


If you have a single JSON string representing an array of objects:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

If you have an array of objects:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

…and you want JSON representation for it, then:

// JSON string representing an array of objects
var json = JSON.stringify(s);

…or if you want a JavaScript array of JSON strings, then:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);

finding first day of the month in python

Yes, first set a datetime to the start of the current month.

Second test if current date day > 25 and get a true/false on that. If True then add add one month to the start of month datetime object. If false then use the datetime object with the value set to the beginning of the month.

import datetime 
from dateutil.relativedelta import relativedelta

todayDate = datetime.date.today()
resultDate = todayDate.replace(day=1)

if ((todayDate - resultDate).days > 25):
    resultDate = resultDate + relativedelta(months=1)

print resultDate

iPhone App Minus App Store?

If you patch /Developer/Platforms/iPhoneOS.platform/Info.plist and then try to debug a application running on the device using a real development provisionen profile from Apple it will probably not work. Symptoms are weird error messages from com.apple.debugserver and that you can use any bundle identifier without getting a error when building in Xcode. The solution is to restore Info.plist.

show/hide a div on hover and hover out

May be there no need for JS. You can achieve this with css also. Write like this:

.flyout {
    position: absolute;
    width: 1000px;
    height: 450px;
    background: red;
    overflow: hidden;
    z-index: 10000;
    display: none;
}
#menu:hover + .flyout {
    display: block;
}

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Java 8 stream map on entry set

Here is a shorter solution by AbacusUtil

Stream.of(input).toMap(e -> e.getKey().substring(subLength), 
                       e -> AttributeType.GetByName(e.getValue()));

Getting first and last day of the current month

DateTime now = DateTime.Now;
var startDate = new DateTime(now.Year, now.Month, 1);
var endDate = startDate.AddMonths(1).AddDays(-1);

How to get a random number between a float range?

Most commonly, you'd use:

import random
random.uniform(a, b) # range [a, b) or [a, b] depending on floating-point rounding

Python provides other distributions if you need.

If you have numpy imported already, you can used its equivalent:

import numpy as np
np.random.uniform(a, b) # range [a, b)

Again, if you need another distribution, numpy provides the same distributions as python, as well as many additional ones.

How to output a comma delimited list in jinja python template?

you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:

{{ users|join(', ') }}

How to loop through elements of forms with JavaScript?

A modern ES6 approach. Select the form with any method you like. Use the spread operator to convert HTMLFormControlsCollection to an Array, then the forEach method is available. [...form.elements].forEach

Update: Array.from is a nicer alternative to spread Array.from(form.elements) it's slightly clearer behaviour.


An example below iterates over every input in the form. You can filter out certain input types by checking input.type != "submit"

_x000D_
_x000D_
const forms = document.querySelectorAll('form');
const form = forms[0];

Array.from(form.elements).forEach((input) => {
  console.log(input);
});
_x000D_
<div>
  <h1>Input Form Selection</h1>
  <form>
    <label>
      Foo
      <input type="text" placeholder="Foo" name="Foo" />
    </label>
    <label>
      Password
      <input type="password" placeholder="Password" />
    </label>
    <label>
      Foo
      <input type="text" placeholder="Bar" name="Bar" />
    </label>
    <span>Ts &amp; Cs</span>
    <input type="hidden" name="_id" />
    <input type="submit" name="_id" />
  </form>
</div>
_x000D_
_x000D_
_x000D_

How to get the command line args passed to a running process on unix/linux systems?

On Linux, with bash, to output as quoted args so you can edit the command and rerun it

</proc/"${pid}"/cmdline xargs --no-run-if-empty -0 -n1 \
    bash -c 'printf "%q " "${1}"' /dev/null; echo

On Solaris, with bash (tested with 3.2.51(1)-release) and without gnu userland:

IFS=$'\002' tmpargs=( $( pargs "${pid}" \
    | /usr/bin/sed -n 's/^argv\[[0-9]\{1,\}\]: //gp' \
    | tr '\n' '\002' ) )
for tmparg in "${tmpargs[@]}"; do
    printf "%q " "$( echo -e "${tmparg}" )"
done; echo

Linux bash Example (paste in terminal):

{
## setup intial args
argv=( /bin/bash -c '{ /usr/bin/sleep 10; echo; }' /dev/null 'BEGIN {system("sleep 2")}' "this is" \
    "some" "args "$'\n'" that" $'\000' $'\002' "need" "quot"$'\t'"ing" )

## run in background
"${argv[@]}" &

## recover into eval string that assigns it to argv_recovered
eval_me=$(
    printf "argv_recovered=( "
    </proc/"${!}"/cmdline xargs --no-run-if-empty -0 -n1 \
        bash -c 'printf "%q " "${1}"' /dev/null
    printf " )\n"
)

## do eval
eval "${eval_me}"

## verify match
if [ "$( declare -p argv )" == "$( declare -p argv_recovered | sed 's/argv_recovered/argv/' )" ];
then
    echo MATCH
else
    echo NO MATCH
fi
}

Output:

MATCH

Solaris Bash Example:

{
## setup intial args
argv=( /bin/bash -c '{ /usr/bin/sleep 10; echo; }' /dev/null 'BEGIN {system("sleep 2")}' "this is" \
    "some" "args "$'\n'" that" $'\000' $'\002' "need" "quot"$'\t'"ing" )

## run in background
"${argv[@]}" &
pargs "${!}"
ps -fp "${!}"

declare -p tmpargs
eval_me=$(
    printf "argv_recovered=( "
    IFS=$'\002' tmpargs=( $( pargs "${!}" \
        | /usr/bin/sed -n 's/^argv\[[0-9]\{1,\}\]: //gp' \
        | tr '\n' '\002' ) )
    for tmparg in "${tmpargs[@]}"; do
        printf "%q " "$( echo -e "${tmparg}" )"
    done; echo
    printf " )\n"
)

## do eval
eval "${eval_me}"


## verify match
if [ "$( declare -p argv )" == "$( declare -p argv_recovered | sed 's/argv_recovered/argv/' )" ];
then
    echo MATCH
else
    echo NO MATCH
fi
}

Output:

MATCH

how to convert .java file to a .class file

Use the javac program that comes with the JDK (visit java.sun.com if you don't have it). The installer does not automatically add javac to your system path, so you'll need to add the bin directory of the installed path to your system path before you can use it easily.

Correct file permissions for WordPress

It actually depends on the plugins you plan to use as some plugins change the root document of the wordpress. but generally I recommend something like this for the wordpress directory.

This will assign the "root" (or whatever the user you are using) as the user in every single file/folder, R means recursive, so it just doesn't stop at the "html" folder. if you didn't use R, then it only applicable to the "html" directory.

sudo chown -R root:www-data /var/www/html  

This will set the owner/group of "wp-content" to "www-data" and thus allowing the web server to install the plugins through the admin panel.

chown -R www-data:www-data /var/www/html/wp-content

This will set the permission of every single file in "html" folder (Including files in subdirectories) to 644, so outside people can't execute any file, modify any file, group can't execute any file, modify any file and only the user is allowed to modify/read files, but still even the user can't execute any file. This is important because it prevents any kind of execution in "html" folder, also since the owner of the html folder and all other folders except the wp-content folder are "root" (or your user), the www-data can't modify any file outside of the wp-content folder, so even if there is any vulnerability in the web server, and if someone accessed to the site unauthorizedly, they can't delete the main site except the plugins.

sudo find /var/www/html -type f -exec chmod 644 {} +

This will restrict the permission of accessing to "wp-config.php" to user/group with rw-r----- these permissions.

chmod 640 /var/www/html/wp-config.php

And if a plugin or update complained it can't update, then access to the SSH and use this command, and grant the temporary permission to "www-data" (web server) to update/install through the admin panel, and then revert back to the "root" or your user once it's completed.

chown -R www-data /var/www/html

And in Nginx (same procedure for the apache)to protect the wp-admin folder from unauthorized accessing, and probing. apache2-utils is required for encrypting the password even if you have nginx installed, omit c if you plan to add more users to the same file.

sudo apt-get install apache2-utils
sudo htpasswd -c /etc/nginx/.htpasswd userName

Now visit this location

/etc/nginx/sites-available/

Use this codes to protect "wp-admin" folder with a password, now it will ask the password/username if you tried to access to the "wp-admin". notice, here you use the ".htpasswd" file which contains the encrypted password.

location ^~ /wp-admin {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
    index  index.php index.html index.htm;
}

Now restart the nginx.

sudo /etc/init.d/nginx restart

ASP.NET postback with JavaScript

You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

Iterating a JavaScript object's properties using jQuery

Late, but can be done by using Object.keys like,

_x000D_
_x000D_
var a={key1:'value1',key2:'value2',key3:'value3',key4:'value4'},_x000D_
  ulkeys=document.getElementById('object-keys'),str='';_x000D_
var keys = Object.keys(a);_x000D_
for(i=0,l=keys.length;i<l;i++){_x000D_
   str+= '<li>'+keys[i]+' : '+a[keys[i]]+'</li>';_x000D_
}_x000D_
ulkeys.innerHTML=str;
_x000D_
<ul id="object-keys"></ul>
_x000D_
_x000D_
_x000D_

How to set character limit on the_content() and the_excerpt() in wordpress

Or even easier and without the need to create a filter: use PHP's mb_strimwidth to truncate a string to a certain width (length). Just make sure you use one of the get_ syntaxes. For example with the content:

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>

This will cut the string at 400 characters and close it with .... Just add a "read more"-link to the end by pointing to the permalink with get_permalink().

<a href="<?php the_permalink() ?>">Read more </a>

Of course you could also build the read more in the first line. Than just replace '...' with '<a href="' . get_permalink() . '">[Read more]</a>'

Apply CSS rules to a nested class inside a div

Use Css Selector for this, or learn more about Css Selector just go here https://www.w3schools.com/cssref/css_selectors.asp

#main_text > .title {
  /* Style goes here */
}

#main_text .title {
  /* Style goes here */
}

How to search all loaded scripts in Chrome Developer Tools?

Search All Files with Control+Shift+F or Console->[Search tab]

enter image description here

NOTE: Global Search shows up next to the CONSOLE menu

Concatenate text files with Windows command line, dropping leading lines

The help for copy explains that wildcards can be used to concatenate multiple files into one.

For example, to copy all .txt files in the current folder that start with "abc" into a single file named xyz.txt:

copy abc*.txt xyz.txt

Is there a command to undo git init?

remove the .git folder in your project root folder

if you installed submodules and want to remove their git, also remove .git from submodules folders

Elegant Python function to convert CamelCase to snake_case?

Wow I just stole this from django snippets. ref http://djangosnippets.org/snippets/585/

Pretty elegant

camelcase_to_underscore = lambda str: re.sub(r'(?<=[a-z])[A-Z]|[A-Z](?=[^A-Z])', r'_\g<0>', str).lower().strip('_')

Example:

camelcase_to_underscore('ThisUser')

Returns:

'this_user'

REGEX DEMO

ASP.NET MVC Razor pass model to layout

old question but just to mention the solution for MVC5 developers, you can use the Model property same as in view.

The Model property in both view and layout is assosiated with the same ViewDataDictionary object, so you don't have to do any extra work to pass your model to the layout page, and you don't have to declare @model MyModelName in the layout.

But notice that when you use @Model.XXX in the layout the intelliSense context menu will not appear because the Model here is a dynamic object just like ViewBag.

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

If you just want to delete the address assigned to the user and not to affect on User entity class you should try something like that:

@Entity
public class User {
   @OneToMany(mappedBy = "addressOwner", cascade = CascadeType.ALL)
   protected Set<Address> userAddresses = new HashSet<>();
}

@Entity 
public class Addresses {
   @ManyToOne(cascade = CascadeType.REFRESH) @JoinColumn(name = "user_id")
   protected User addressOwner;
}

This way you dont need to worry about using fetch in annotations. But remember when deleting the User you will also delete connected address to user object.

How do I write to the console from a Laravel Controller?

For better explain Dave Morrissey's answer I have made these steps for wrap with Console Output class in a laravel facade.

1) Create a Facade in your prefer folder (in my case app\Facades):

class ConsoleOutput extends Facade {

 protected static function getFacadeAccessor() { 
     return 'consoleOutput';
 }

}

2) Register a new Service Provider in app\Providers as follow:

class ConsoleOutputServiceProvider extends ServiceProvider
{

 public function register(){
    App::bind('consoleOutput', function(){
        return new \Symfony\Component\Console\Output\ConsoleOutput();
     });
 }

}

3) Add all this stuffs in config\app.php file, registering the provider and alias.

 'providers' => [
   //other providers
    App\Providers\ConsoleOutputServiceProvider::class
 ],
 'aliases' => [
  //other aliases
   'ConsoleOutput' => App\Facades\ConsoleOutput::class,
 ],

That's it, now in any place of your Laravel application, just call your method in this way:

ConsoleOutput::writeln('hello');

Hope this help you.

Getting All Variables In Scope

Yes and no. "No" in almost every situation. "Yes," but only in a limited manner, if you want to check the global scope. Take the following example:

var a = 1, b = 2, c = 3;

for ( var i in window ) {
    console.log(i, typeof window[i], window[i]);
}

Which outputs, amongst 150+ other things, the following:

getInterface function getInterface()
i string i // <- there it is!
c number 3
b number 2
a number 1 // <- and another
_firebug object Object firebug=1.4.5 element=div#_firebugConsole
"Firebug command line does not support '$0'"
"Firebug command line does not support '$1'"
_FirebugCommandLine object Object
hasDuplicate boolean false

So it is possible to list some variables in the current scope, but it is not reliable, succinct, efficient, or easily accessible.

A better question is why do you want to know what variables are in scope?

Issue when importing dataset: `Error in scan(...): line 1 did not have 145 elements`

I encountered this error when I had a row.names="id" (per the tutorial) with a column named "id".

How to center a <p> element inside a <div> container?

This solution works fine for all major browsers, except IE. So keep that in mind.

In this example, basicaly I use positioning, horizontal and vertical transform for the UI element to center it.

_x000D_
_x000D_
        .container {_x000D_
            /* set the the position to relative */_x000D_
            position: relative;_x000D_
            width: 30rem;_x000D_
            height: 20rem;_x000D_
            background-color: #2196F3;_x000D_
        }_x000D_
_x000D_
_x000D_
        .paragh {_x000D_
            /* set the the position to absolute */_x000D_
            position: absolute;_x000D_
            /* set the the position of the helper container into the middle of its space */_x000D_
            top: 50%;_x000D_
            left: 50%;_x000D_
            font-size: 30px;_x000D_
            /* make sure padding and margin do not disturb the calculation of the center point */_x000D_
            padding: 0;_x000D_
            margin: 0;_x000D_
            /* using centers for the transform */_x000D_
            transform-origin: center center;_x000D_
            /* calling calc() function for the calculation to move left and up the element from the center point */_x000D_
            transform: translateX(calc((100% / 2) * (-1))) translateY(calc((100% / 2) * (-1)));_x000D_
        }
_x000D_
<div class="container">_x000D_
    <p class="paragh">Text</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I hope this help.

Are static methods inherited in Java?

You can experience the difference in following code, which is slightly modification over your code.

class A {
    public static void display() {
        System.out.println("Inside static method of superclass");
    }
}

class B extends A {
    public void show() {
        display();
    }

    public static void display() {
        System.out.println("Inside static method of this class");
    }
}

public class Test {
    public static void main(String[] args) {
        B b = new B();
        // prints: Inside static method of this class
        b.display();

        A a = new B();
        // prints: Inside static method of superclass
        a.display();
    }
}

This is due to static methods are class methods.

A.display() and B.display() will call method of their respective classes.

Laravel Escaping All HTML in Blade Template

There is no problem with displaying HTML code in blade templates.

For test, you can add to routes.php only one route:

Route::get('/', function () {

        $data = new stdClass();
        $data->page_desc
            = '<strong>aaa</strong><em>bbb</em>
               <p>New paragaph</p><script>alert("Hello");</script>';

        return View::make('hello')->with('content', $data);
    }
);

and in hello.blade.php file:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>

{{ $content->page_desc }}

</body>
</html>

For the following code you will get output as on image

Output

So probably page_desc in your case is not what you expect. But as you see it can be potential dangerous if someone uses for example '` tag so you should probably in your route before assigning to blade template filter some tags

EDIT

I've also tested it with putting the same code into database:

Route::get('/', function () {

        $data = User::where('id','=',1)->first();

        return View::make('hello')->with('content', $data);
    }
);

Output is exactly the same in this case

Edit2

I also don't know if Pages is your model or it's a vendor model. For example it can have accessor inside:

public function getPageDescAttribute($value)
{
    return htmlspecialchars($value);
}

and then when you get page_desc attribute you will get modified page_desc with htmlspecialchars. So if you are sure that data in database is with raw html (not escaped) you should look at this Pages class

Returning null in a method whose signature says return int?

int is a primitive data type . It is not a reference variable which can take null values . You need to change the method return type to Integer wrapper class .

MySQL "WITH" clause

Have you ever tried Temporary Table? This solved my convern:

create temporary table abc (
column1 varchar(255)
column2 decimal
);
insert into abc
select ...
or otherwise
insert into abc
values ('text', 5.5), ('text2', 0815.8);

Then you can use this table in every select in this session:

select * from abc inner join users on ...;

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

Quick fix for CGRectMake , CGPointMake, CGSizeMake in Swift3 & iOS10

Add these extensions :

extension CGRect{
    init(_ x:CGFloat,_ y:CGFloat,_ width:CGFloat,_ height:CGFloat) {
        self.init(x:x,y:y,width:width,height:height)
    }

}
extension CGSize{
    init(_ width:CGFloat,_ height:CGFloat) {
        self.init(width:width,height:height)
    }
}
extension CGPoint{
    init(_ x:CGFloat,_ y:CGFloat) {
        self.init(x:x,y:y)
    }
}

Then go to "Find and Replace in Workspace" Find CGRectMake , CGPointMake, CGSizeMake and Replace them with CGRect , CGPoint, CGSize

These steps might save all the time as Xcode right now doesn't give us quick conversion from Swift 2+ to Swift 3

1030 Got error 28 from storage engine

My /tmp was %100. After removing all files and restarting mysql everything worked fine.

Can't connect to docker from docker-compose

if you are using docker-machine then you have to activate the environment using env variable. incase you are not using docker-machine then run your commands with sudo

Django: How can I call a view function from template?

Assuming that you want to get a value from the user input in html textbox whenever the user clicks 'Click' button, and then call a python function (mypythonfunction) that you wrote inside mypythoncode.py. Note that "btn" class is defined in a css file.

inside templateHTML.html:

<form action="#" method="get">
 <input type="text" value="8" name="mytextbox" size="1"/>
 <input type="submit" class="btn" value="Click" name="mybtn">
</form>

inside view.py:

import mypythoncode

def request_page(request):
  if(request.GET.get('mybtn')):
    mypythoncode.mypythonfunction( int(request.GET.get('mytextbox')) )
return render(request,'myApp/templateHTML.html')

Need to navigate to a folder in command prompt

Navigate to the folder in Windows Explorer, highlight the complete folder path in the top pane and type "cmd" - voila!

How do I make a stored procedure in MS Access?

Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).

If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.

For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.

For example:

screenshot

Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table alt text

Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.

R Markdown - changing font size and font type in html output

I would definitely use html markers to achieve this. Just surround your text with <p></p> or <font></font> and add the desired attributes. See the following example:

<p style="font-family: times, serif; font-size:11pt; font-style:italic">
    Why did we use these specific parameters during the calculation of the fingerprints?
</p>

This will produce the following output

Font Output

compared to

Default Output

This would work with Jupyter Notebook as well as Typora, but I'm not sure if it is universal.

Lastly, be aware that the html marker overrides the font styling used by Markdown.

Convert string to datetime in vb.net

Pass the decode pattern to ParseExact

Dim d as string = "201210120956"
Dim dt = DateTime.ParseExact(d, "yyyyMMddhhmm", Nothing)

ParseExact is available only from Net FrameWork 2.0.
If you are still on 1.1 you could use Parse, but you need to provide the IFormatProvider adequate to your string

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

I faced the same issue, It got fixed after keeping issuer subject value in the certificate as it is as subject of issuer certificate.

so please check "issuer subject value in the certificate(cert.pem) == subject of issuer (CA.pem)"

openssl verify -CAfile CA.pem cert.pem
cert.pem: OK

Dockerfile copy keep subdirectory structure

Alternatively you can use a "." instead of *, as this will take all the files in the working directory, include the folders and subfolders:

FROM ubuntu
COPY . /
RUN ls -la /

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.

Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.

The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

How to trap the backspace key using jQuery?

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

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

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

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

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

       // Add your code here.
     }
});

Stripping everything but alphanumeric chars from a string in Python

If i understood correctly the easiest way is to use regular expression as it provides you lots of flexibility but the other simple method is to use for loop following is the code with example I also counted the occurrence of word and stored in dictionary..

s = """An... essay is, generally, a piece of writing that gives the author's own 
argument — but the definition is vague, 
overlapping with those of a paper, an article, a pamphlet, and a short story. Essays 
have traditionally been 
sub-classified as formal and informal. Formal essays are characterized by "serious 
purpose, dignity, logical 
organization, length," whereas the informal essay is characterized by "the personal 
element (self-revelation, 
individual tastes and experiences, confidential manner), humor, graceful style, 
rambling structure, unconventionality 
or novelty of theme," etc.[1]"""

d = {}      # creating empty dic      
words = s.split() # spliting string and stroing in list
for word in words:
    new_word = ''
    for c in word:
        if c.isalnum(): # checking if indiviual chr is alphanumeric or not
            new_word = new_word + c
    print(new_word, end=' ')
    # if new_word not in d:
    #     d[new_word] = 1
    # else:
    #     d[new_word] = d[new_word] +1
print(d)

please rate this if this answer is useful!

How do you count the elements of an array in java

int theArray[] = new int[20];
System.out.println(theArray.length);

TypeError: object of type 'int' has no len() error assistance needed

Abstract:

The reason why you are getting this error message is because you are trying to call a method on an int type of a variable. This would work if would have called len() function on a list type of a variable. Let's examin the two cases:

Fail:

num = 10

print(len(num))

The above will produce an error similar to yours due to calling len() function on an int type of a variable;

Success:

data = [0, 4, 8, 9, 12]

print(len(data))

The above will work since you are calling a function on a list type of a variable;

scp (secure copy) to ec2 instance without password

Just tested:

Run the following command:

sudo shred -u /etc/ssh/*_key /etc/ssh/*_key.pub

Then:

  1. create ami (image of the ec2).
  2. launch from new ami(image) from step no 2 chose new keys.

How to add a new project to Github using VS Code

Yes you can upload your git repo from vs code. You have to get in the projects working directory and type git init in the terminal. Then add the files to your repository like you do with regular git commits.

Inheriting constructors

Correct Code is

class A
{
    public: 
      explicit A(int x) {}
};

class B: public A
{
      public:

     B(int a):A(a){
          }
};

main()
{
    B *b = new B(5);
     delete b;
}

Error is b/c Class B has not parameter constructor and second it should have base class initializer to call the constructor of Base Class parameter constructor

How can I use regex to get all the characters after a specific character, e.g. comma (",")

You don't need regex to do this. Here's an example :

var str = "'SELECT___100E___7',24";
var afterComma = str.substr(str.indexOf(",") + 1); // Contains 24 //

how to convert an RGB image to numpy array?

OpenCV image format supports the numpy array interface. A helper function can be made to support either grayscale or color images. This means the BGR -> RGB conversion can be conveniently done with a numpy slice, not a full copy of image data.

Note: this is a stride trick, so modifying the output array will also change the OpenCV image data. If you want a copy, use .copy() method on the array!

import numpy as np

def img_as_array(im):
    """OpenCV's native format to a numpy array view"""
    w, h, n = im.width, im.height, im.channels
    modes = {1: "L", 3: "RGB", 4: "RGBA"}
    if n not in modes:
        raise Exception('unsupported number of channels: {0}'.format(n))
    out = np.asarray(im)
    if n != 1:
        out = out[:, :, ::-1]  # BGR -> RGB conversion
    return out

Make the size of a heatmap bigger with seaborn

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

Kotlin unresolved reference in IntelliJ

I had this issue because the linter was printing that my object was an instance of Foo whereas the compiler couldn't define its type and consider it was an Any object like (It was more complex in my case, the linter show error in below code but the idea is here) :

    class Foo {
        val bar: Int = 0
    }

    fun test(): Any {
        return Foo()
    }

    val foo = test()
    foo.bar // <-- Linter consider that foo is an Instance of Foo but not the compiler because it's an Any object so it show the error at compilation.

To fix it I had to cast my object :

val foo = test() as Foo

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

Now aiming to an actual solution, covering all possible cases of input in the 8 digit range with only 1MB of RAM. NOTE: work in progress, tomorrow will continue. Using arithmetic coding of deltas of the sorted ints, worst case for 1M sorted ints would cost about 7bits per entry (since 99999999/1000000 is 99, and log2(99) is almost 7 bits).

But you need the 1m integers sorted to get to 7 or 8 bits! Shorter series would have bigger deltas, therefore more bits per element.

I'm working on taking as many as possible and compressing (almost) in-place. First batch of close to 250K ints would need about 9 bits each at best. So result would take about 275KB. Repeat with remaining free memory a few times. Then decompress-merge-in-place-compress those compressed chunks. This is quite hard, but possible. I think.

The merged lists would get closer and closer to the 7bit per integer target. But I don't know how many iterations it would take of the merge loop. Perhaps 3.

But the imprecision of the arithmetic coding implementation might make it impossible. If this problem is possible at all, it would be extremely tight.

Any volunteers?

Install a module using pip for specific python version

You can use this syntax

python_version -m pip install your_package

For example. If you're running python3.5, you named it as "python3", and want to install numpy package

python3 -m pip install numpy

How to send json data in POST request using C#

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:

using (var client = new HttpClient())
{
    // This would be the like http://www.uber.com
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   
}

ERROR 1044 (42000): Access denied for 'root' With All Privileges

If you get an error 1044 (42000) when you try to run SQL commands in MySQL (which installed along XAMPP server) cmd prompt, then here's the solution:

  1. Close your MySQL command prompt.

  2. Open your cmd prompt (from Start menu -> run -> cmd) which will show: C:\Users\User>_

  3. Go to MySQL.exe by Typing the following commands:

C:\Users\User>cd\ C:\>cd xampp C:\xampp>cd mysql C:\xxampp\mysql>cd bin C:\xampp\mysql\bin>mysql -u root

  1. Now try creating a new database by typing:

    mysql> create database employee;
    

    if it shows:

    Query OK, 1 row affected (0.00 sec)
    mysql>
    

    Then congrats ! You are good to go...

IIS7 Cache-Control

The F5 Refresh has the semantic of "please reload the current HTML AND its direct dependancies". Hence you should expect to see any imgs, css and js resource directly referenced by the HTML also being refetched. Of course a 304 is an acceptable response to this but F5 refresh implies that the browser will make the request rather than rely on fresh cache content.

Instead try simply navigating somewhere else and then navigating back.

You can force the refresh, past a 304, by holding ctrl while pressing f5 in most browsers.

Get custom product attributes in Woocommerce

You can get the single value for the attribute with below code:

$pa_koostis_value = get_post_meta($product->id, 'pa_koostis', true);

How do I delete everything in Redis?

redis-cli -h <host> -p <port> flushall

It will remove all data from client connected(with host and port)

Get user's non-truncated Active Directory groups from command line

You could parse the output from the GPRESULT command.

How do I print a double value with full precision using cout?

printf("%.12f", M_PI);

%.12f means floating point, with precision of 12 digits.

Insert a line break in mailto body

For the Single line and double line break here are the following codes.

Single break: %0D0A
Double break: %0D0A%0D0A

Python Iterate Dictionary by Index

Some of the comments are right in saying that these answers do not correspond to the question.

One reason one might want to loop through a dictionary using "indexes" is for example to compute a distance matrix for a set of objects in a dictionary. To put it as an example (going a bit to the basics on the bullet below):

  • Assuming one have 1000 objects on a dictionary, the distance square matrix consider all combinations from one object to any other and so it would have dimensions of 1000x1000 elements. But if the distance from object 1 to object 2 is the same as from object 2 to object 1, one need to compute the distance only to less than half of the square matrix, since the diagonal will have distance 0 and the values are mirrored above and below the diagonal.

This is why most packages use a condensed distance matrix ( How does condensed distance matrix work? (pdist) )

But consider the case one is implementing the computation of a distance matrix, or any kind of permutation of the sort. In such case you need to skip the results from more than half of the cases. This means that a FOR loop that runs through all the dictionary is just hitting an IF and jumping to the next iteration without performing really any job most of the time. For large datasets this additional "IFs" and loops add up to a relevant amount on the processing time and could be avoided if, at each loop, one starts one "index" further on the dictionary.

Going than to the question, my conclusion right now is that the answer is NO. One has no way to directly access the dictionary values by any index except the key or an iterator.

I understand that most of the answers up to now applies different approaches to perform this task but really don't allow any index manipulation, that would be useful in a case such as exemplified.

The only alternative I see is to use a list or other variable as a sequential index to the dictionary. Here than goes an implementation to exemplify such case:

#!/usr/bin/python3

dishes = {'spam': 4.25, 'eggs': 1.50, 'sausage': 1.75, 'bacon': 2.00}
print("Dictionary: {}\n".format(dishes))

key_list = list(dishes.keys())
number_of_items = len(key_list)

condensed_matrix = [0]*int(round(((number_of_items**2)-number_of_items)/2,0))
c_m_index = 0

for first_index in range(0,number_of_items):
    for second_index in range(first_index+1,number_of_items):
        condensed_matrix[c_m_index] = dishes[key_list[first_index]] - dishes[key_list[second_index]]
        print("{}. {}-{} = {}".format(c_m_index,key_list[first_index],key_list[second_index],condensed_matrix[c_m_index]))
        c_m_index+=1

The output is:

Dictionary: {'spam': 4.25, 'eggs': 1.5, 'sausage': 1.75, 'bacon': 2.0}

0. spam-eggs = 2.75
1. spam-sausage = 2.5
2. spam-bacon = 2.25
3. eggs-sausage = -0.25
4. eggs-bacon = -0.5
5. sausage-bacon = -0.25

Its also worth mentioning that are packages such as intertools that allows one to perform similar tasks in a shorter format.

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

Many times as API's are updated. We forgot to update SDK Managers. For accessing recent API's one should always have highest API Level updated if possible should also have other regularly used lower level APIs to accommodate backward compatibility.
Go to build.gradle (module.app) file change compileSdkVersion buildToolsVersion targetSdkVersion, all should have the highest level of API.

What's the best way to detect a 'touch screen' device using JavaScript?

We tried the modernizr implementation, but detecting the touch events is not consistent anymore (IE 10 has touch events on windows desktop, IE 11 works, because the've dropped touch events and added pointer api).

So we decided to optimize the website as a touch site as long as we don't know what input type the user has. This is more reliable than any other solution.

Our researches say, that most desktop users move with their mouse over the screen before they click, so we can detect them and change the behaviour before they are able to click or hover anything.

This is a simplified version of our code:

var isTouch = true;
window.addEventListener('mousemove', function mouseMoveDetector() {
    isTouch = false;
    window.removeEventListener('mousemove', mouseMoveDetector);
});

Declaring static constants in ES6 classes?

Here's a few things you could do:

Export a const from the module. Depending on your use case, you could just:

export const constant1 = 33;

And import that from the module where necessary. Or, building on your static method idea, you could declare a static get accessor:

const constant1 = 33,
      constant2 = 2;
class Example {

  static get constant1() {
    return constant1;
  }

  static get constant2() {
    return constant2;
  }
}

That way, you won't need parenthesis:

const one = Example.constant1;

Babel REPL Example

Then, as you say, since a class is just syntactic sugar for a function you can just add a non-writable property like so:

class Example {
}
Object.defineProperty(Example, 'constant1', {
    value: 33,
    writable : false,
    enumerable : true,
    configurable : false
});
Example.constant1; // 33
Example.constant1 = 15; // TypeError

It may be nice if we could just do something like:

class Example {
    static const constant1 = 33;
}

But unfortunately this class property syntax is only in an ES7 proposal, and even then it won't allow for adding const to the property.

Making heatmap from pandas DataFrame

Useful sns.heatmap api is here. Check out the parameters, there are a good number of them. Example:

import seaborn as sns
%matplotlib inline

idx= ['aaa','bbb','ccc','ddd','eee']
cols = list('ABCD')
df = DataFrame(abs(np.random.randn(5,4)), index=idx, columns=cols)

# _r reverses the normal order of the color map 'RdYlGn'
sns.heatmap(df, cmap='RdYlGn_r', linewidths=0.5, annot=True)

enter image description here

belongs_to through associations

My approach was to make a virtual attribute instead of adding database columns.

class Choice
  belongs_to :user
  belongs_to :answer

  # ------- Helpers -------
  def question
    answer.question
  end

  # extra sugar
  def question_id
    answer.question_id
  end
end

This approach is pretty simple, but comes with tradeoffs. It requires Rails to load answer from the db, and then question. This can be optimized later by eager loading the associations you need (i.e. c = Choice.first(include: {answer: :question})), however, if this optimization is necessary, then stephencelis' answer is probably a better performance decision.

There's a time and place for certain choices, and I think this choice is better when prototyping. I wouldn't use it for production code unless I knew it was for an infrequent use case.

Detect iPhone/iPad purely by css

iPhone & iPod touch:

<link rel="stylesheet" media="only screen and (max-device-width: 480px)" href="../iphone.css" type="text/css" />

iPhone 4 & iPod touch 4G:

<link rel="stylesheet" media="only screen and (-webkit-min-device-pixel-ratio: 2)" type="text/css" href="../iphone4.css" />

iPad:

<link rel="stylesheet" media="only screen and (max-device-width: 1024px)" href="../ipad.css" type="text/css" />

How to add Android Support Repository to Android Studio?

I used to get similar issues. Even after installing the support repository, the build used to fail.

Basically the issues is due to the way the version number of the jar files are specified in the gradle files are specified properly.

For example, in my case i had set it as "compile 'com.android.support:support-v4:21.0.3+'"

On removing "+" the build was sucessful!!

Cassandra port usage - how are the ports used?

In addition to the above answers, as part of configuring your firewall, if you are using SSH then use port 22.

How to determine if object is in array

try Array.prototype.some()

MDN Array.prototype.some


    function isBiggerThan10(element, index, array) {
      return element > 10;
    }
    [2, 5, 8, 1, 4].some(isBiggerThan10);  // false
    [12, 5, 8, 1, 4].some(isBiggerThan10); // true

How do I reset a sequence in Oracle?

Here's a more robust procedure for altering the next value returned by a sequence, plus a whole lot more.

  • First off it protects against SQL injection attacks since none of the strings passed in are used to directly create any of the dynamic SQL statements,
  • Second it prevents the next sequence value from being set outside the bounds of the min or max sequence values. The next_value will be != min_value and between min_value and max_value.
  • Third it takes the current (or proposed) increment_by setting as well as all the other sequence settings into account when cleaning up.
  • Fourth all parameters except the first are optional and unless specified take on the current sequence setting as defaults. If no optional parameters are specified no action is taken.
  • Finally if you try altering a sequence that doesn't exist (or is not owned by the current user) it will raise an ORA-01403: no data found error.

Here's the code:

CREATE OR REPLACE PROCEDURE alter_sequence(
    seq_name      user_sequences.sequence_name%TYPE
  , next_value    user_sequences.last_number%TYPE := null
  , increment_by  user_sequences.increment_by%TYPE := null
  , min_value     user_sequences.min_value%TYPE := null
  , max_value     user_sequences.max_value%TYPE := null
  , cycle_flag    user_sequences.cycle_flag%TYPE := null
  , cache_size    user_sequences.cache_size%TYPE := null
  , order_flag    user_sequences.order_flag%TYPE := null)
  AUTHID CURRENT_USER
AS
  l_seq user_sequences%rowtype;
  l_old_cache user_sequences.cache_size%TYPE;
  l_next user_sequences.min_value%TYPE;
BEGIN
  -- Get current sequence settings as defaults
  SELECT * INTO l_seq FROM user_sequences WHERE sequence_name = seq_name;

  -- Update target settings
  l_old_cache := l_seq.cache_size;
  l_seq.increment_by := nvl(increment_by, l_seq.increment_by);
  l_seq.min_value    := nvl(min_value, l_seq.min_value);
  l_seq.max_value    := nvl(max_value, l_seq.max_value);
  l_seq.cycle_flag   := nvl(cycle_flag, l_seq.cycle_flag);
  l_seq.cache_size   := nvl(cache_size, l_seq.cache_size);
  l_seq.order_flag   := nvl(order_flag, l_seq.order_flag);

  IF next_value is NOT NULL THEN
    -- Determine next value without exceeding limits
    l_next := LEAST(GREATEST(next_value, l_seq.min_value+1),l_seq.max_value);

    -- Grab the actual latest seq number
    EXECUTE IMMEDIATE
        'ALTER SEQUENCE '||l_seq.sequence_name
            || ' INCREMENT BY 1'
            || ' MINVALUE '||least(l_seq.min_value,l_seq.last_number-l_old_cache)
            || ' MAXVALUE '||greatest(l_seq.max_value,l_seq.last_number)
            || ' NOCACHE'
            || ' ORDER';
    EXECUTE IMMEDIATE 
      'SELECT '||l_seq.sequence_name||'.NEXTVAL FROM DUAL'
    INTO l_seq.last_number;

    l_next := l_next-l_seq.last_number-1;

    -- Reset the sequence number
    IF l_next <> 0 THEN
      EXECUTE IMMEDIATE 
        'ALTER SEQUENCE '||l_seq.sequence_name
            || ' INCREMENT BY '||l_next
            || ' MINVALUE '||least(l_seq.min_value,l_seq.last_number)
            || ' MAXVALUE '||greatest(l_seq.max_value,l_seq.last_number)
            || ' NOCACHE'
            || ' ORDER';
      EXECUTE IMMEDIATE 
        'SELECT '||l_seq.sequence_name||'.NEXTVAL FROM DUAL'
      INTO l_next;
    END IF;
  END IF;

  -- Prepare Sequence for next use.
  IF COALESCE( cycle_flag
             , next_value
             , increment_by
             , min_value
             , max_value
             , cache_size
             , order_flag) IS NOT NULL
  THEN
    EXECUTE IMMEDIATE 
      'ALTER SEQUENCE '||l_seq.sequence_name
          || ' INCREMENT BY '||l_seq.increment_by
          || ' MINVALUE '||l_seq.min_value
          || ' MAXVALUE '||l_seq.max_value
          || CASE l_seq.cycle_flag
             WHEN 'Y' THEN ' CYCLE' ELSE ' NOCYCLE' END
          || CASE l_seq.cache_size
             WHEN 0 THEN ' NOCACHE'
             ELSE ' CACHE '||l_seq.cache_size END
          || CASE l_seq.order_flag
             WHEN 'Y' THEN ' ORDER' ELSE ' NOORDER' END;
  END IF;
END;

Setting environment variables on OS X

My personal practice is .bash_profile. I'm adding paths there and append to Path variable,

GOPATH=/usr/local/go/bin/
MYSQLPATH=/usr/local/opt/[email protected]/bin

PATH=$PATH:$GOPATH:$MYSQLPATH

After then I can have individual Path by echo $GOPATH, echo$MYSQLPATH or all by echo $PATH.

WPF Image Dynamically changing Image source during runtime

Hey, this one is kind of ugly but it's one line only:

imgTitle.Source = new BitmapImage(new Uri(@"pack://application:,,,/YourAssembly;component/your_image.png"));

Convert any object to a byte[]

I'd rather use the expression "serialization" than "casting into bytes". Serializing an object means converting it into a byte array (or XML, or something else) that can be used on the remote box to re-construct the object. In .NET, the Serializable attribute marks types whose objects can be serialized.

How to restore SQL Server 2014 backup in SQL Server 2008

If you have both versions you can create a merge replication from new to old. Create a merge publication on your newer sql server and a subscription on the older version. After initializing the subscription you can create a backup of the database with the same structure and the same content but in an older version and restore it on your old target server. You can use this method also with sql server 2016 to target 2014, 2012 or 2008.

good postgresql client for windows?

EMS's SQL Manager is much easier to use and has many more features than either phpPgAdmin or PG Admin III. However, it's windows only and you have to pay for it.

How to center div vertically inside of absolutely positioned parent div

You can do it by using display:table; in parent div and display: table-cell; vertical-align: middle; in child div

_x000D_
_x000D_
<div style="display:table;">_x000D_
      <div style="text-align: left;  height: 56px;  background-color: pink; display: table-cell; vertical-align: middle;">_x000D_
          <div style="background-color: lightblue; ">test</div>_x000D_
      </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How to launch Windows Scheduler by command-line?

I'm using Windows 2003 on the server. I'm in action with "SCHTASKS.EXE"

    SCHTASKS /parameter [arguments]

    Description:
        Enables an administrator to create, delete, query, change, run and
        end scheduled tasks on a local or remote system. Replaces AT.exe.

    Parameter List:
        /Create         Creates a new scheduled task.

        /Delete         Deletes the scheduled task(s).

        /Query          Displays all scheduled tasks.

        /Change         Changes the properties of scheduled task.

        /Run            Runs the scheduled task immediately.

        /End            Stops the currently running scheduled task.

        /?              Displays this help message.

    Examples:
        SCHTASKS
        SCHTASKS /?
        SCHTASKS /Run /?
        SCHTASKS /End /?
        SCHTASKS /Create /?
        SCHTASKS /Delete /?
        SCHTASKS /Query  /?
        SCHTASKS /Change /?

    +-------------------------------------+
    ¦ Executed Wed 02/29/2012 10:48:36.65 ¦
    +-------------------------------------+

It's quite interesting and makes me feel so powerful. :)

how to know status of currently running jobs

Given a job (I assume you know its name) you can use:

EXEC msdb.dbo.sp_help_job @Job_name = 'Your Job Name'

as suggested in MSDN Job Help Procedure. It returns a lot of informations about the job (owner, server, status and so on).

Calculate number of hours between 2 dates in PHP

//Calculate number of hours between pass and now
$dayinpass = "2013-06-23 05:09:12";
$today = time();
$dayinpass= strtotime($dayinpass);
echo round(abs($today-$dayinpass)/60/60);

Representing EOF in C code?

EOF is not a character (in most modern operating systems). It is simply a condition that applies to a file stream when the end of the stream is reached. The confusion arises because a user may signal EOF for console input by typing a special character (e.g Control-D in Unix, Linux, et al), but this character is not seen by the running program, it is caught by the operating system which in turn signals EOF to the process.

Note: in some very old operating systems EOF was a character, e.g. Control-Z in CP/M, but this was a crude hack to avoid the overhead of maintaining actual file lengths in file system directories.

startForeground fail after upgrade to Android 8.1

After some tinkering for a while with different solutions i found out that one must create a notification channel in Android 8.1 and above.

private fun startForeground() {
    val channelId =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                createNotificationChannel("my_service", "My Background Service")
            } else {
                // If earlier version channel ID is not used
                // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
                ""
            }

    val notificationBuilder = NotificationCompat.Builder(this, channelId )
    val notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setPriority(PRIORITY_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build()
    startForeground(101, notification)
}

@RequiresApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(channelId: String, channelName: String): String{
    val chan = NotificationChannel(channelId,
            channelName, NotificationManager.IMPORTANCE_NONE)
    chan.lightColor = Color.BLUE
    chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
    val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    service.createNotificationChannel(chan)
    return channelId
}

From my understanding background services are now displayed as normal notifications that the user then can select to not show by deselecting the notification channel.

Update: Also don't forget to add the foreground permission as required Android P:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

React hooks useState Array

To expand on Ryan's answer:

Whenever setStateValues is called, React re-renders your component, which means that the function body of the StateSelector component function gets re-executed.

React docs:

setState() will always lead to a re-render unless shouldComponentUpdate() returns false.

Essentially, you're setting state with:

setStateValues(allowedState);

causing a re-render, which then causes the function to execute, and so on. Hence, the loop issue.

To illustrate the point, if you set a timeout as like:

  setTimeout(
    () => setStateValues(allowedState),
    1000
  )

Which ends the 'too many re-renders' issue.

In your case, you're dealing with a side-effect, which is handled with UseEffectin your component functions. You can read more about it here.

How do you rename a Git tag?

In addition to the other answers:

First you need to build an alias of the old tag name, pointing to the original commit:

git tag new old^{}

Then you need to delete the old one locally:

git tag -d old

Then delete the tag on you remote location(s):

# Check your remote sources:
git remote -v
# The argument (3rd) is your remote location,
# the one you can see with `git remote`. In this example: `origin`
git push origin :refs/tags/old

Finally you need to add your new tag to the remote location. Until you have done this, the new tag(s) will not be added:

git push origin --tags

Iterate this for every remote location.

Be aware, of the implications that a Git Tag change has to consumers of a package!

cannot connect to pc-name\SQLEXPRESS

Follow these steps then you solve your problem 100%.

  1. When you get this error then close everything(Microsoft SQL Server Managment):

error

  1. Then open command prompt by pressing (window + r) keys and type services.msc and click OK or press Enter key.

  2. And search **SQL Server (SQLEXPRESS) as I show in the image.

enter image description here

  1. Now see left upper side and click start.

  2. If you open Microsoft SQL Server Management then you not get any type error.

Enjoy!!!

Converting int to string in C

see this example

#include <stdlib.h> // for itoa() call
#include <stdio.h>  

int main() {
    int num = 145;
    char buf[5];

    // convert 123 to string [buf]
    itoa(num, buf, 10);

    // print our string
    printf("%s\n", buf);

    return 0;
}

see this link having other examples.

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

@JS5 , I also faced the same issue as you: ImageButton causing exceptions inside UpdatePanel only on production server and IE. After some research I found this:

There is an issue with ImageButtons and UpdatePanels. The update to .NET 4.5 is fixed there. It has something to do with Microsoft changed the x,y axis of a button click from Int to Double so you can tell where on the button you clicked and it's throwing a conversion error.

Source

I'm using NetFramework 2.0 and IIS 6, so, the suggested solution was to downgrade IE compatibility adding a meta tag:

<meta http-equiv="X-UA-Compatible" content="IE=9" />

I've done this via Page_Load method only on the page I needed to:

Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    Dim tag As HtmlMeta = New HtmlMeta()

    tag.HttpEquiv = "X-UA-Compatible"
    tag.Content = "IE=9"

    Header.Controls.Add(tag)
End Sub

Hope this helps someone.

How do I solve the "server DNS address could not be found" error on Windows 10?

Steps to manually configure DNS:

  1. You can access Network and Sharing center by right clicking on the Network icon on the taskbar.

  2. Now choose adapter settings from the side menu.

  3. This will give you a list of the available network adapters in the system . From them right click on the adapter you are using to connect to the internet now and choose properties option.

  4. In the networking tab choose ‘Internet Protocol Version 4 (TCP/IPv4)’.

  5. Now you can see the properties dialogue box showing the properties of IPV4. Here you need to change some properties.

    Select ‘use the following DNS address’ option. Now fill the following fields as given here.

    Preferred DNS server: 208.67.222.222

    Alternate DNS server : 208.67.220.220

    This is an available Open DNS address. You may also use google DNS server addresses.

    After filling these fields. Check the ‘validate settings upon exit’ option. Now click OK.

You have to add this DNS server address in the router configuration also (by referring the router manual for more information).

Refer : for above method & alternative

If none of this works, then open command prompt(Run as Administrator) and run these:

ipconfig /flushdns
ipconfig /registerdns
ipconfig /release
ipconfig /renew
NETSH winsock reset catalog
NETSH int ipv4 reset reset.log
NETSH int ipv6 reset reset.log
Exit

Hopefully that fixes it, if its still not fixed there is a chance that its a NIC related issue(driver update or h/w).

Also FYI, this has a thread on Microsoft community : Windows 10 - DNS Issue

commons httpclient - Adding query string parameters to GET/POST request

This approach is ok but will not work for when you get params dynamically , sometimes 1, 2, 3 or more, just like a SOLR search query (for example)

Here is a more flexible solution. Crude but can be refined.

public static void main(String[] args) {

    String host = "localhost";
    String port = "9093";

    String param = "/10-2014.01?description=cars&verbose=true&hl=true&hl.simple.pre=<b>&hl.simple.post=</b>";
    String[] wholeString = param.split("\\?");
    String theQueryString = wholeString.length > 1 ? wholeString[1] : "";

    String SolrUrl = "http://" + host + ":" + port + "/mypublish-services/carclassifications/" + "loc";

    GetMethod method = new GetMethod(SolrUrl );

    if (theQueryString.equalsIgnoreCase("")) {
        method.setQueryString(new NameValuePair[]{
        });
    } else {
        String[] paramKeyValuesArray = theQueryString.split("&");
        List<String> list = Arrays.asList(paramKeyValuesArray);
        List<NameValuePair> nvPairList = new ArrayList<NameValuePair>();
        for (String s : list) {
            String[] nvPair = s.split("=");
            String theKey = nvPair[0];
            String theValue = nvPair[1];
            NameValuePair nameValuePair = new NameValuePair(theKey, theValue);
            nvPairList.add(nameValuePair);
        }
        NameValuePair[] nvPairArray = new NameValuePair[nvPairList.size()];
        nvPairList.toArray(nvPairArray);
        method.setQueryString(nvPairArray);       // Encoding is taken care of here by setQueryString

    }
}

Is there a constraint that restricts my generic method to numeric types?

Considering the popularity of this question and the interest behind such a function I am surprised to see that there is no answer involving T4 yet.

In this sample code I will demonstrate a very simple example of how you can use the powerful templating engine to do what the compiler pretty much does behind the scenes with generics.

Instead of going through hoops and sacrificing compile-time certainty you can simply generate the function you want for every type you like and use that accordingly (at compile time!).

In order to do this:

  • Create a new Text Template file called GenericNumberMethodTemplate.tt.
  • Remove the auto-generated code (you'll keep most of it, but some isn't needed).
  • Add the following snippet:
<#@ template language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>

<# Type[] types = new[] {
    typeof(Int16), typeof(Int32), typeof(Int64),
    typeof(UInt16), typeof(UInt32), typeof(UInt64)
    };
#>

using System;
public static class MaxMath {
    <# foreach (var type in types) { 
    #>
        public static <#= type.Name #> Max (<#= type.Name #> val1, <#= type.Name #> val2) {
            return val1 > val2 ? val1 : val2;
        }
    <#
    } #>
}

That's it. You're done now.

Saving this file will automatically compile it to this source file:

using System;
public static class MaxMath {
    public static Int16 Max (Int16 val1, Int16 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static Int32 Max (Int32 val1, Int32 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static Int64 Max (Int64 val1, Int64 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt16 Max (UInt16 val1, UInt16 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt32 Max (UInt32 val1, UInt32 val2) {
        return val1 > val2 ? val1 : val2;
    }
    public static UInt64 Max (UInt64 val1, UInt64 val2) {
        return val1 > val2 ? val1 : val2;
    }
}

In your main method you can verify that you have compile-time certainty:

namespace TTTTTest
{
    class Program
    {
        static void Main(string[] args)
        {
            long val1 = 5L;
            long val2 = 10L;
            Console.WriteLine(MaxMath.Max(val1, val2));
            Console.Read();
        }
    }
}

enter image description here

I'll get ahead of one remark: no, this is not a violation of the DRY principle. The DRY principle is there to prevent people from duplicating code in multiple places that would cause the application to become hard to maintain.

This is not at all the case here: if you want a change then you can just change the template (a single source for all your generation!) and it's done.

In order to use it with your own custom definitions, add a namespace declaration (make sure it's the same one as the one where you'll define your own implementation) to your generated code and mark the class as partial. Afterwards, add these lines to your template file so it will be included in the eventual compilation:

<#@ import namespace="TheNameSpaceYouWillUse" #>
<#@ assembly name="$(TargetPath)" #>

Let's be honest: This is pretty cool.

Disclaimer: this sample has been heavily influenced by Metaprogramming in .NET by Kevin Hazzard and Jason Bock, Manning Publications.

IIS - can't access page by ip address instead of localhost

Check the settings of the browser proxy . For me it helped , traffic was directed outside.

How to convert an array of strings to an array of floats in numpy?

Well, if you're reading the data in as a list, just do np.array(map(float, list_of_strings)) (or equivalently, use a list comprehension). (In Python 3, you'll need to call list on the map return value if you use map, since map returns an iterator now.)

However, if it's already a numpy array of strings, there's a better way. Use astype().

import numpy as np
x = np.array(['1.1', '2.2', '3.3'])
y = x.astype(np.float)

How do I login and authenticate to Postgresql after a fresh install?

you can also connect to database as "normal" user (not postgres):

postgres=# \connect opensim Opensim_Tester localhost;

Password for user Opensim_Tester:    

You are now connected to database "opensim" as user "Opensim_Tester" on host "localhost" at port "5432"

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

Don't reload the page - this brings the error message up again. Instead, start at the beginning of the URL you were looking at a second ago, and delete everything before it. Then press enter. The error won't come back for at least another little while.

I know because FanFiction.net has the same problem, and this is how I've solved it.

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

Android java.lang.NoClassDefFoundError

Try going to Project -> Properties -> Java Build Path -> Order & Export And Confirm Android Private Libraries are checked for your project and for all other library projects you are using in your Application.

How do I get the offset().top value of an element without using jQuery?

the accepted solution by Patrick Evans doesn't take scrolling into account. i've slightly changed his jsfiddle to demonstrate this:

css: add some random height to make sure we got some space to scroll

body{height:3000px;} 

js: set some scroll position

jQuery(window).scrollTop(100);

as a result the two reported values differ now: http://jsfiddle.net/sNLMe/66/

UPDATE Feb. 14 2015

there is a pull request for jqLite waiting, including its own offset method (taking care of current scroll position). have a look at the source in case you want to implement it yourself: https://github.com/angular/angular.js/pull/3799/files

How do I select last 5 rows in a table without sorting?

There is a handy trick that works in some databases for ordering in database order,

SELECT * FROM TableName ORDER BY true

Apparently, this can work in conjunction with any of the other suggestions posted here to leave the results in "order they came out of the database" order, which in some databases, is the order they were last modified in.

How to change the Push and Pop animations in a navigation based app

You can now use UIView.transition. Note that animated:false. This works with any transition option, pop, push, or stack replace.

if let nav = self.navigationController
{
    UIView.transition(with:nav.view, duration:0.3, options:.transitionCrossDissolve, animations: {
        _ = nav.popViewController(animated:false)
    }, completion:nil)
}

How does a Breadth-First Search work when looking for Shortest Path?

The following solution works for all the test cases.

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

   public static void main(String[] args)
        {
            Scanner sc = new Scanner(System.in);

            int testCases = sc.nextInt();

            for (int i = 0; i < testCases; i++)
            {
                int totalNodes = sc.nextInt();
                int totalEdges = sc.nextInt();

                Map<Integer, List<Integer>> adjacencyList = new HashMap<Integer, List<Integer>>();

                for (int j = 0; j < totalEdges; j++)
                {
                    int src = sc.nextInt();
                    int dest = sc.nextInt();

                    if (adjacencyList.get(src) == null)
                    {
                        List<Integer> neighbours = new ArrayList<Integer>();
                        neighbours.add(dest);
                        adjacencyList.put(src, neighbours);
                    } else
                    {
                        List<Integer> neighbours = adjacencyList.get(src);
                        neighbours.add(dest);
                        adjacencyList.put(src, neighbours);
                    }


                    if (adjacencyList.get(dest) == null)
                    {
                        List<Integer> neighbours = new ArrayList<Integer>();
                        neighbours.add(src);
                        adjacencyList.put(dest, neighbours);
                    } else
                    {
                        List<Integer> neighbours = adjacencyList.get(dest);
                        neighbours.add(src);
                        adjacencyList.put(dest, neighbours);
                    }
                }

                int start = sc.nextInt();

                Queue<Integer> queue = new LinkedList<>();

                queue.add(start);

                int[] costs = new int[totalNodes + 1];

                Arrays.fill(costs, 0);

                costs[start] = 0;

                Map<String, Integer> visited = new HashMap<String, Integer>();

                while (!queue.isEmpty())
                {
                    int node = queue.remove();

                    if(visited.get(node +"") != null)
                    {
                        continue;
                    }

                    visited.put(node + "", 1);

                    int nodeCost = costs[node];

                    List<Integer> children = adjacencyList.get(node);

                    if (children != null)
                    {
                        for (Integer child : children)
                        {
                            int total = nodeCost + 6;
                            String key = child + "";

                            if (visited.get(key) == null)
                            {
                                queue.add(child);

                                if (costs[child] == 0)
                                {
                                    costs[child] = total;
                                } else if (costs[child] > total)
                                {
                                    costs[child] = total;
                                }
                            }
                        }
                    }
                }

                for (int k = 1; k <= totalNodes; k++)
                {
                    if (k == start)
                    {
                        continue;
                    }

                    System.out.print(costs[k] == 0 ? -1 : costs[k]);
                    System.out.print(" ");
                }
                System.out.println();
            }
        }
}

htaccess - How to force the client's browser to clear the cache?

This worked for me.

look for this:

    DirectoryIndex index.php

replace with this:

    DirectoryIndex something.php index.php

Upload and refresh page. You will get a page error.

just change it back to:

    DirectoryIndex index.php

reupload and refresh page again.
I checked this on all of my devices and, it worked.

AngularJs .$setPristine to reset form

Had a similar problem, where I had to set the form back to pristine, but also to untouched, since $invalid and $error were both used to show error messages. Only using setPristine() was not enough to clear the error messages.

I solved it by using setPristine() and setUntouched(). (See Angular's documentation: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController)

So, in my controller, I used:

$scope.form.setPristine(); 
$scope.form.setUntouched();

These two functions reset the complete form to $pristine and back to $untouched, so that all error messages were cleared.

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

Call child method from parent

You can make Inheritance Inversion (look it up here: https://medium.com/@franleplant/react-higher-order-components-in-depth-cf9032ee6c3e). That way you have access to instance of the component that you would be wrapping (thus you'll be able to access it's functions)

How do you disable viewport zooming on Mobile Safari?

Using the CSS touch-action property is the most elegant solution. Tested on iOS 13.5 and iOS 14.

To disable pinch zoom gestures and and double-tap to zoom:

body {
  touch-action: pan-x pan-y;
}

If your app also has no need for panning, i.e. scrolling, use this:

body {
  touch-action: none;
}

How to install SQL Server Management Studio 2008 component only

The accepted answer was correct up until July 2011. To get the latest version, including the Service Pack you should find the latest version as described here:

For example, if you check the SP2 CTP and SP1, you'll find the latest version of SQL Server Management Studio under SP1:

Download the 32-bit (x86) or 64-bit (x64) version of the SQLManagementStudio*.exe files as appropriate and install it. You can find out whether your system is 32-bit or 64-bit by right clicking Computer, selecting Properties and looking at the System Type.

Although you could apply the service pack to the base version that results from following the accepted answer, it's easier to just download the latest version of SQL Server Management Studio and simply install it in one step.

How do I check if an HTML element is empty using jQuery?

If by "empty", you mean with no HTML content,

if($('#element').html() == "") {
  //call function
}

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

This is a very big problem. What actually happens in your code is this:

  • You load Parent from the database and get an attached entity
  • You replace its child collection with new collection of detached children
  • You save changes but during this operation all children are considered as added becasue EF didn't know about them till this time. So EF tries to set null to foreign key of old children and insert all new children => duplicate rows.

Now the solution really depends on what you want to do and how would you like to do it?

If you are using ASP.NET MVC you can try to use UpdateModel or TryUpdateModel.

If you want just update existing children manually, you can simply do something like:

foreach (var child in modifiedParent.ChildItems)
{
    context.Childs.Attach(child); 
    context.Entry(child).State = EntityState.Modified;
}

context.SaveChanges();

Attaching is actually not needed (setting the state to Modified will also attach the entity) but I like it because it makes the process more obvious.

If you want to modify existing, delete existing and insert new childs you must do something like:

var parent = context.Parents.GetById(1); // Make sure that childs are loaded as well
foreach(var child in modifiedParent.ChildItems)
{
    var attachedChild = FindChild(parent, child.Id);
    if (attachedChild != null)
    {
        // Existing child - apply new values
        context.Entry(attachedChild).CurrentValues.SetValues(child);
    }
    else
    {
        // New child
        // Don't insert original object. It will attach whole detached graph
        parent.ChildItems.Add(child.Clone());
    }
}

// Now you must delete all entities present in parent.ChildItems but missing
// in modifiedParent.ChildItems
// ToList should make copy of the collection because we can't modify collection
// iterated by foreach
foreach(var child in parent.ChildItems.ToList())
{
    var detachedChild = FindChild(modifiedParent, child.Id);
    if (detachedChild == null)
    {
        parent.ChildItems.Remove(child);
        context.Childs.Remove(child); 
    }
}

context.SaveChanges();

sorting a List of Map<String, String>

try {
        java.util.Collections.sort(data,
                new Comparator<Map<String, String>>() {
                    SimpleDateFormat sdf = new SimpleDateFormat(
                            "MM/dd/yyyy");

                    public int compare(final Map<String, String> map1,
                            final Map<String, String> map2) {
                        Date date1 = null, date2 = null;
                        try {
                            date1 = sdf.parse(map1.get("Date"));
                            date2 = sdf.parse(map2.get("Date"));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (date1.compareTo(date2) > 0) {
                            return +1;
                        } else if (date1.compareTo(date2) == 0) {
                            return 0;
                        } else {
                            return -1;
                        }
                    }
                });

    } catch (Exception e) {

    }

Calculate Age in MySQL (InnoDb)

Simply do

SELECT birthdate, (YEAR(CURDATE())-YEAR(birthdate)) AS age FROM `member` 

birthdate is field name that keep birthdate name take CURDATE() turn to year by YEAR() command minus with YEAR() from the birthdate field

Best Practice to Use HttpClient in Multithreaded Environment

I think you will want to use ThreadSafeClientConnManager.

You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html

Or in the AndroidHttpClient which uses it internally.

How do I write a bash script to restart a process if it dies?

I'm not sure how portable it is across operating systems, but you might check if your system contains the 'run-one' command, i.e. "man run-one". Specifically, this set of commands includes 'run-one-constantly', which seems to be exactly what is needed.

From man page:

run-one-constantly COMMAND [ARGS]

Note: obviously this could be called from within your script, but also it removes the need for having a script at all.

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

The current path of MyScript1.ps1 is not the same as myScript2.ps1. You can get the folder path of MyScript2.ps1 and concatenate it to MyScript1.ps1 and then execute it. Both scripts must be in the same location.

## MyScript2.ps1 ##
$ScriptPath = Split-Path $MyInvocation.InvocationName
& "$ScriptPath\MyScript1.ps1"

Android studio, gradle and NDK

UPDATE: The Android Studio with NDK support is out now: http://tools.android.com/tech-docs/android-ndk-preview

For building with a script the gradle solution below should work:

I am using my build script and added to my file (Seems to work for 0.8+): This seems to be equivalent to the solution below (but looks nicer in the gradle file):

 android {
    sourceSets {
        main {
            jniLibs.srcDirs = ['native-libs']
            jni.srcDirs = [] //disable automatic ndk-build
        }
    }
 }

The build unfortunately does not fail if the directory is not present or contains no .so files.

Converting <br /> into a new line for use in a text area

i am use following construction to convert back nl2br

function br2nl( $input ) {
    return preg_replace('/<br\s?\/?>/ius', "\n", str_replace("\n","",str_replace("\r","", htmlspecialchars_decode($input))));
}

here i replaced \n and \r symbols from $input because nl2br dosen't remove them and this causes wrong output with \n\n or \r<br>.