Programs & Examples On #Walkthrough

How to set up Automapper in ASP.NET Core

Step To Use AutoMapper with ASP.NET Core.

Step 1. Installing AutoMapper.Extensions.Microsoft.DependencyInjection from NuGet Package.

enter image description here

Step 2. Create a Folder in Solution to keep Mappings with Name "Mappings".

enter image description here

Step 3. After adding Mapping folder we have added a class with Name "MappingProfile" this name can anything unique and good to understand.

In this class, we are going to Maintain all Mappings.

enter image description here

Step 4. Initializing Mapper in Startup "ConfigureServices"

In Startup Class, we Need to Initialize Profile which we have created and also Register AutoMapper Service.

  Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());

  services.AddAutoMapper();

Code Snippet to show ConfigureServices Method where we need to Initialize and Register AutoMapper.

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }


    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });


        // Start Registering and Initializing AutoMapper

        Mapper.Initialize(cfg => cfg.AddProfile<MappingProfile>());
        services.AddAutoMapper();

        // End Registering and Initializing AutoMapper

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    }}

Step 5. Get Output.

To Get Mapped result we need to call AutoMapper.Mapper.Map and pass Proper Destination and Source.

AutoMapper.Mapper.Map<Destination>(source);

CodeSnippet

    [HttpPost]
    public void Post([FromBody] SchemeMasterViewModel schemeMaster)
    {
        if (ModelState.IsValid)
        {
            var mappedresult = AutoMapper.Mapper.Map<SchemeMaster>(schemeMaster);
        }
    }

IsNumeric function in c#

It is worth mentioning that one can check the characters in the string against Unicode categories - numbers, uppercase, lowercase, currencies and more. Here are two examples checking for numbers in a string using Linq:

var containsNumbers = s.Any(Char.IsNumber);
var isNumber = s.All(Char.IsNumber);

For clarity, the syntax above is a shorter version of:

var containsNumbers = s.Any(c=>Char.IsNumber(c));
var isNumber = s.All(c=>Char.IsNumber(c));

Link to unicode categories on MSDN:

UnicodeCategory Enumeration

What is the connection string for localdb for version 11

You need to install Dot Net 4.0.2 or above as mentioned here.
The 4.0 bits don't understand the syntax required by LocalDB

See this question here

You can dowload the update here

Performing a Stress Test on Web Application?

Try ZebraTester which is much easier to use than jMeter. I have used jMeter for a long time but the total setup time for a load test was always an issue. Although ZebraTester isn't open source, the time that I have saved in the last six months makes up for it. They also have a SaaS portal which can be used for quickly running tests using their load generators.

SQL Server find and replace specific word in all rows of specific column

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')
WHERE number like 'KIT%'

or simply this if you are sure that you have no values like this CKIT002

UPDATE tblKit
SET number = REPLACE(number, 'KIT', 'CH')

Applying function with multiple arguments to create a new pandas column

This solves the problem:

df['newcolumn'] = df.A * df.B

You could also do:

def fab(row):
  return row['A'] * row['B']

df['newcolumn'] = df.apply(fab, axis=1)

MVVM Passing EventArgs As Command Parameter

For people just finding this post, you should know that in newer versions (not sure on the exact version since official docs are slim on this topic) the default behavior of the InvokeCommandAction, if no CommandParameter is specified, is to pass the args of the event it's attached to as the CommandParameter. So the originals poster's XAML could be simply written as:

<i:Interaction.Triggers>
  <i:EventTrigger EventName="Navigated">
    <i:InvokeCommandAction Command="{Binding NavigatedEvent}"/>
  </i:EventTrigger>
</i:Interaction.Triggers>

Then in your command, you can accept a parameter of type NavigationEventArgs (or whatever event args type is appropriate) and it will automatically be provided.

Why should I use an IDE?

It really depends on what language you're using, but in C# and Java I find IDEs beneficial for:

  • Quickly navigating to a type without needing to worry about namespace, project etc
  • Navigating to members by treating them as hyperlinks
  • Autocompletion when you can't remember the names of all members by heart
  • Automatic code generation
  • Refactoring (massive one)
  • Organise imports (automatically adding appropriate imports in Java, using directives in C#)
  • Warning-as-you-type (i.e. some errors don't even require a compile cycle)
  • Hovering over something to see the docs
  • Keeping a view of files, errors/warnings/console/unit tests etc and source code all on the screen at the same time in a useful way
  • Ease of running unit tests from the same window
  • Integrated debugging
  • Integrated source control
  • Navigating to where a compile-time error or run-time exception occurred directly from the error details.
  • Etc!

All of these save time. They're things I could do manually, but with more pain: I'd rather be coding.

Overflow:hidden dots at the end

<style>
    .dots
    {
        display: inline-block;
        width: 325px;
        white-space: nowrap;
        overflow: hidden !important;
        text-overflow: ellipsis;
    }

    .dot
    {
        display: inline-block;
        width: 185px;
        white-space: nowrap;
        overflow: hidden !important;
        text-overflow: ellipsis;
    }
</style>

Bootstrap Accordion button toggle "data-parent" not working

Bootstrap 4

Use the data-parent="" attribute on the collapse element (instead of the trigger element)

<div id="accordion">
  <div class="card">
    <div class="card-header">
      <h5>
        <button class="btn btn-link" data-toggle="collapse" data-target="#collapseOne">
          Collapsible #1 trigger
        </button>
      </h5>
    </div>
    <div id="collapseOne" class="collapse show" data-parent="#accordion">
      <div class="card-body">
        Collapsible #1 element
      </div>
    </div>
  </div>
  ... (more cards/collapsibles inside #accordion parent)
</div>

Bootstrap 3

See this issue on GitHub: https://github.com/twbs/bootstrap/issues/10966

There is a "bug" that makes the accordion dependent on the .panel class when using the data-parent attribute. To workaround it, you can wrap each accordion group in a 'panel' div..

http://bootply.com/88288

<div class="accordion" id="myAccordion">
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-1" data-parent="#myAccordion">Question 1?</button>
        <div id="collapsible-1" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-2" data-parent="#myAccordion">Question 2?</button>
        <div id="collapsible-2" class="collapse">
            ..
        </div>
    </div>
    <div class="panel">
        <button type="button" class="btn btn-danger" data-toggle="collapse" data-target="#collapsible-3" data-parent="#myAccordion">Question 3?</button>
        <div id="collapsible-3" class="collapse">
           ...
        </div>
    </div>
</div>

Edit

As mentioned in the comments, each section doesn't have to be a .panel. However...

  • .panel must be a direct child of the element used as data-parent=
  • each accordion section (data-toggle=) must be a direct child of the .panel (http://www.bootply.com/AbiRW7BdD6#)

Convert integers to strings to create output filenames at run time

Try the following:

    ....
    character(len=30) :: filename  ! length depends on expected names
    integer           :: inuit
    ....
    do i=1,n
        write(filename,'("output",i0,".txt")') i
        open(newunit=iunit,file=filename,...)
        ....
        close(iunit)
    enddo
    ....

Where "..." means other appropriate code for your purpose.

Insert multiple lines into a file after specified pattern using shell script

You can use awk for inserting output of some command in the middle of input.txt.
The lines to be inserted can be the output of a cat otherfile, ls -l or 4 lines with a number generated by printf.

awk 'NR==FNR {a[NR]=$0;next}
    {print}
    /cdef/ {for (i=1; i <= length(a); i++) { print a[i] }}'
    <(printf "%s\n" line{1..4}) input.txt

how do I join two lists using linq or lambda expressions

 public class State
        {
            public int SID { get; set; }
            public string SName { get; set; }
            public string SCode { get; set; }
            public string SAbbrevation { get; set; }
        }

        public class Country
        {
            public int CID { get; set; }
            public string CName { get; set; }
            public string CAbbrevation { get; set; }
        }


 List<State> states = new List<State>()
            {
               new  State{  SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
               new  State{  SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
            };

            List<Country> coutries = new List<Country>()
            {
               new Country{CID=1,CName="India",CAbbrevation="IND"},
               new Country{CID=2,CName="US of America",CAbbrevation="USA"},
            };

            var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();

Generate random password string with requirements in javascript

Based on @Ryan Shillington answer above you may find this enhancment helpfull too. Think this is more secured then what was requeted on the original request in the question above.

  1. Password generated with at least 1 number, 1 upper case character, 1 lower case character and 1 Special character
  2. Password length is dynamic

_x000D_
_x000D_
//Password generated with at least 1 number, 1 upper case character, 1 lower case character and 1 Special character
function generatePassword() 
{
      var passwordLength = randomIntFromInterval(10,20);    
      var numberChars = "0123456789";
      var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      var lowerChars = "abcdefghijklmnopqrstuvwxyz";
      var specialChars = "~!#$%&*-+|";
      var allChars = numberChars + upperChars + lowerChars + specialChars;
      var randPasswordArray = Array(passwordLength);
      randPasswordArray[0] = numberChars;
      randPasswordArray[1] = upperChars;
      randPasswordArray[2] = lowerChars;
      randPasswordArray[3] = specialChars;
      randPasswordArray = randPasswordArray.fill(allChars, 4);
      if(window.crypto && window.crypto.getRandomValues)
      {
          return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(window.crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)] })).join('');  
      }
      else if(window.msCrypto && window.msCrypto.getRandomValues) 
      {
          return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(window.msCrypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1) * x.length)] })).join('');
      }else{
          return shuffleArray(randPasswordArray.map(function(x) { return x[Math.floor(Math.random() * x.length)] })).join('');
      }
      
    }

    function shuffleArray(array) 
    {
      for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
     
     return array;
}

//generate random number in the range (min and max included)
function randomIntFromInterval(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
}
_x000D_
<input type='text' id='p9'/>
<input type='button' value ='pass generator' onclick='document.getElementById("p9").value = generatePassword()'>
_x000D_
_x000D_
_x000D_

Global variables in Java

without static this is possible too:

class Main {
  String globalVar = "Global Value";

  class Class1 {
    Class1() {
      System.out.println("Class1: "+globalVar);
      globalVar += " - changed";
  } }
  class Class2 {
    Class2() {
      System.out.println("Class2: "+globalVar);
  } }

  public static void main(String[] args) {  
    Main m = new Main();
    m.mainCode();
  }
  void mainCode() {
    Class1 o1 = new Class1();
    Class2 o2 = new Class2();
  }
}

/*
Output:
Class1: Global Value
Class2: Global Value - changed
*/

UITableView - scroll to the top

DONT USE

 tableView.setContentOffset(.zero, animated: true)

It can sometimes set the offset improperly. For example, in my case, the cell was actually slightly above the view with safe area insets. Not good.

INSTEAD USE

 tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)

Create a dictionary with list comprehension

Here is another example of dictionary creation using dict comprehension:

What i am tring to do here is to create a alphabet dictionary where each pair; is the english letter and its corresponding position in english alphabet

>>> import string
>>> dict1 = {value: (int(key) + 1) for key, value in 
enumerate(list(string.ascii_lowercase))}
>>> dict1
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4, 'g': 7, 'f': 6, 'i': 9, 'h': 8, 
'k': 11, 'j': 10, 'm': 13, 'l': 12, 'o': 15, 'n': 14, 'q': 17, 'p': 16, 's': 
19, 'r': 18, 'u': 21, 't': 20, 'w': 23, 'v': 22, 'y': 25, 'x': 24, 'z': 26}
>>> 

Notice the use of enumerate here to get a list of alphabets and their indexes in the list and swapping the alphabets and indices to generate the key value pair for dictionary

Hope it gives a good idea of dictionary comp to you and encourages you to use it more often to make your code compact

SQL SERVER: Get total days between two dates

This is working for me -

SELECT DATEDIFF(DAY, startdate, enddate) AS DayCount

Example : SELECT DATEDIFF(DAY, '11/30/2019', GETDATE()) AS DayCount

"OverflowError: Python int too large to convert to C long" on windows but not mac

You'll get that error once your numbers are greater than sys.maxsize:

>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

You can confirm this by checking:

>>> import sys
>>> sys.maxsize
2147483647

To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:

>>> preds = np.zeros((1, 3))

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

Also, if your service is sending an object instead of an array add isArray:false to its declaration.

'query': {method: 'GET', isArray: false }

In bash, how to store a return value in a variable?

The answer above suggests changing the function to echo data rather than return it so that it can be captured.

For a function or program that you can't modify where the return value needs to be saved to a variable (like test/[, which returns a 0/1 success value), echo $? within the command substitution:

# Test if we're remote.
isRemote="$(test -z "$REMOTE_ADDR"; echo $?)"
# Or:
isRemote="$([ -z "$REMOTE_ADDR" ]; echo $?)"

# Additionally you may want to reverse the 0 (success) / 1 (error) values
# for your own sanity, using arithmetic expansion:
remoteAddrIsEmpty="$([ -z "$REMOTE_ADDR" ]; echo $((1-$?)))"

E.g.

$ echo $REMOTE_ADDR

$ test -z "$REMOTE_ADDR"; echo $?
0
$ REMOTE_ADDR=127.0.0.1
$ test -z "$REMOTE_ADDR"; echo $?
1
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
1
$ unset REMOTE_ADDR
$ retval="$(test -z "$REMOTE_ADDR"; echo $?)"; echo $retval
0

For a program which prints data but also has a return value to be saved, the return value would be captured separately from the output:

# Two different files, 1 and 2.
$ cat 1
1
$ cat 2
2
$ diffs="$(cmp 1 2)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [1] Diffs: [1 2 differ: char 1, line 1]
$ diffs="$(cmp 1 1)"
$ haveDiffs=$?
$ echo "Have differences? [$haveDiffs] Diffs: [$diffs]"
Have differences? [0] Diffs: []

# Or again, if you just want a success variable, reverse with arithmetic expansion:
$ cmp -s 1 2; filesAreIdentical=$((1-$?))
$ echo $filesAreIdentical
0

How to get PID of process by specifying process name and store it in a variable to use further?

pids=$(pgrep <name>)

will get you the pids of all processes with the given name. To kill them all, use

kill -9 $pids

To refrain from using a variable and directly kill all processes with a given name issue

pkill -9 <name>

How do I create 7-Zip archives with .NET?

These easiest way is to work with .zip files instead of .7z and use Dot Net Zip

When spinning off 7zip commands to shell there are other issues like user privileges, I had issue with SevenZipSharp.

Private Function CompressFile(filename As String) As Boolean
Using zip As New ZipFile()
    zip.AddFile(filename & ".txt", "")
    zip.Save(filename & ".zip")
End Using

Return File.Exists(filename & ".zip")
End Function

Copy folder recursively, excluding some folders

Use tar along with a pipe.

cd /source_directory
tar cf - --exclude=dir_to_exclude . | (cd /destination && tar xvf - )

You can even use this technique across ssh.

How to read numbers from file in Python?

Assuming you don't have extraneous whitespace:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()] # read first line
    array = []
    for line in f: # read rest of lines
        array.append([int(x) for x in line.split()])

You could condense the last for loop into a nested list comprehension:

with open('file') as f:
    w, h = [int(x) for x in next(f).split()]
    array = [[int(x) for x in line.split()] for line in f]

Java - How to convert type collection into ArrayList?

As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:

http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29

So you need to do:

ArrayList<MyNode> myNodeList = new ArrayList<MyNode>(this.getVertices());

However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.

I think your code should look like this:

public V getNode(int nodeId){
        ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());
        return myNodeList(nodeId);
}

But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.

Put a Delay in Javascript

I just had an issue where I needed to solve this properly.

Via Ajax, a script gets X (0-10) messages. What I wanted to do: Add one message to the DOM every 10 Seconds.

the code I ended up with:

$.each(messages, function(idx, el){
  window.setTimeout(function(){
    doSomething(el);
  },Math.floor(idx+1)*10000);
});

Basically, think of the timeouts as a "timeline" of your script.

This is what we WANT to code:

DoSomething();
WaitAndDoNothing(5000);
DoSomethingOther();
WaitAndDoNothing(5000);
DoEvenMore();

This is HOW WE NEED TO TELL IT TO THE JAVASCRIPT:

At Runtime 0    : DoSomething();
At Runtime 5000 : DoSomethingOther();
At Runtime 10000: DoEvenMore();

Hope this helps.

Google Maps shows "For development purposes only"

If your mapTypeId is SATELLITE or HYBRID

well, it is just a watermark, you can hide it if you change the <div> that has z-index=100 I use

setInterval(function(){
    $("*").each(function() {
        if ($(this).css("zIndex") == 100) {
            $(this).css("zIndex", "-100");
        }
    })}
, 10);

or you can use

map.addListener('idle', function(e) {
    //same function
}

but it is not as responsive as setInterval

Check whether a cell contains a substring

This is an old question but a solution for those using Excel 2016 or newer is you can remove the need for nested if structures by using the new IFS( condition1, return1 [,condition2, return2] ...) conditional.

I have formatted it to make it visually clearer on how to use it for the case of this question:

=IFS(
ISERROR(SEARCH("String1",A1))=FALSE,"Something1",
ISERROR(SEARCH("String2",A1))=FALSE,"Something2",
ISERROR(SEARCH("String3",A1))=FALSE,"Something3"
)

Since SEARCH returns an error if a string is not found I wrapped it with an ISERROR(...)=FALSE to check for truth and then return the value wanted. It would be great if SEARCH returned 0 instead of an error for readability, but thats just how it works unfortunately.

Another note of importance is that IFS will return the match that it finds first and thus ordering is important. For example if my strings were Surf, Surfing, Surfs as String1,String2,String3 above and my cells string was Surfing it would match on the first term instead of the second because of the substring being Surf. Thus common denominators need to be last in the list. My IFS would need to be ordered Surfing, Surfs, Surf to work correctly (swapping Surfing and Surfs would also work in this simple example), but Surf would need to be last.

How to change value for innodb_buffer_pool_size in MySQL on Mac OS?

In the earlier versions of MySQL ( < 5.7.5 ) the only way to set

'innodb_buffer_pool_size'

variable was by writing it to my.cnf (for linux) and my.ini (for windows) under [mysqld] section :

[mysqld]

innodb_buffer_pool_size = 2147483648

You need to restart your mysql server to have it's effect in action.

UPDATE :

As of MySQL 5.7.5, the innodb_buffer_pool_size configuration option can be set dynamically using a SET statement, allowing you to resize the buffer pool without restarting the server. For example:

mysql> SET GLOBAL innodb_buffer_pool_size=402653184;

Reference : https://dev.mysql.com/doc/refman/5.7/en/innodb-buffer-pool-resize.html

What is compiler, linker, loader?

Hope this helps you a little more.

First, go through this diagram:

(img source->internet)

source->internet

You make a piece of code and save the file (Source code), then

Preprocessing :- As the name suggests, it's not part of compilation. They instruct the compiler to do required pre-processing before the actual compilation. You can call this phase Text Substitution or interpreting special preprocessor directives denoted by #.

Compilation :- Compilation is a process in which a program written in one language get translated into another targeted language. If there is some errors, the compiler will detect them and report it.

Assemble :- Assemble code gets translated into machine code. You can call assembler a special type of complier.

Linking:- If these piece of code needs some other source file to be linked, linker link them to make it a executable file.

There are many process that happens after it. Yes, you guessed it right here comes the role of the loader:

Loader:- It loads the executable code into memory; program and data stack are created, register gets initialized.

Little Extra info :- http://www.geeksforgeeks.org/memory-layout-of-c-program/ , you can see the memory layout over there.

Jquery change <p> text programmatically

Try the following, note that when user refreshes the page, the value is "Male" again, data should be stored on database.

<p id="pTest">Male</p>
<button>change</button>

<script>
$('button').click(function(){
     $('#pTest').text('test')
})
</script>

http://jsfiddle.net/CA5Cs/

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})

For VB.NET this syntax would be accomplished using the dot, ., which in that language is default syntax for all anonymous types:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })

How do I access my SSH public key?

After you generate your SSH key you can do:

cat .ssh/id_rsa.pub |pbcopy

which will copy your ssh key into your clipboard.

Number of times a particular character appears in a string

Look at the length of the string after replacing the sequence

declare @s varchar(10) = 'aabaacaa'
select len(@s) - len(replace(@s, 'a', ''))
>>6

Set Focus After Last Character in Text Box

One can use these simple javascript within the input tag.

<input type="text" name="your_name" value="your_value"
     onfocus="this.setSelectionRange(this.value.length, this.value.length);" 
autofocus />

Adding rows dynamically with jQuery

As an addition to answers above: you probably might need to change ids in names/ids of input elements (pls note, you should not have digits in fields name):

<input name="someStuff.entry[2].fieldOne" id="someStuff_fdf_fieldOne_2" ..>

I have done this having some global variable by default set to 0:

var globalNewIndex = 0;

and in the add function after you've cloned and resetted the values in the new row:

                var newIndex = globalNewIndex+1;
                var changeIds = function(i, val) {
                    return val.replace(globalNewIndex,newIndex);
                }
                $('#mytable tbody>tr:last input').attr('name', changeIds ).attr('id', changeIds );
                globalNewIndex++;

Cannot connect to repo with TortoiseSVN

Run ipconfig /flushdns from a command prompt. Apparently some people seem to think I posted this answer for sheer fun. That's why they down voted my answer. Perhaps an explanation would help them. When I used "SVN Update" it said it can't connect to the SVN repository although I could ping the server. After running ipconfig /flushdns the issue was fixed.

How to obtain Certificate Signing Request

Since you installed a new OS you probably don't have any more of your private and public keys that you used to sign your app in to XCode before. You need to regenerate those keys on your machine by revoking your previous certificate and asking for a new one on the iOS development portal. As part of the process you will be asked to generate a Certificate Signing Request which is where you seem to have a problem.

You will find all you need there which consists of (from the official doc):

1.Open Keychain Access on your Mac (located in Applications/Utilities).

2.Open Preferences and click Certificates. Make sure both Online Certificate Status Protocol and Certificate Revocation List are set to Off.

3.Choose Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority.

Note: If you have a private key selected when you do this, the CSR won’t be accepted. Make sure no private key is selected. Enter your user email address and common name. Use the same address and name as you used to register in the iOS Developer Program. No CA Email Address is required.

4.Select the options “Saved to disk” and “Let me specify key pair information” and click Continue.

5.Specify a filename and click Save. (make sure to replace .certSigningRequest with .csr)

For the Key Size choose 2048 bits and for Algorithm choose RSA. Click Continue and the Certificate Assistant creates a CSR and saves the file to your specified location.

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

Strip spaces/tabs/newlines - python

The above solutions suggesting the use of regex aren't ideal because this is such a small task and regex requires more resource overhead than the simplicity of the task justifies.

Here's what I do:

myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')

or if you had a bunch of things to remove such that a single line solution would be gratuitously long:

removal_list = [' ', '\t', '\n']
for s in removal_list:
  myString = myString.replace(s, '')

BigDecimal equals() versus compareTo()

I see that BigDecimal has an inflate() method on equals() method. What does inflate() do actually?

Basically, inflate() calls BigInteger.valueOf(intCompact) if necessary, i.e. it creates the unscaled value that is stored as a BigInteger from long intCompact. If you don't need that BigInteger and the unscaled value fits into a long BigDecimal seems to try to save space as long as possible.

Select DataFrame rows between two dates

you can do it with pd.date_range() and Timestamp. Let's say you have read a csv file with a date column using parse_dates option:

df = pd.read_csv('my_file.csv', parse_dates=['my_date_col'])

Then you can define a date range index :

rge = pd.date_range(end='15/6/2020', periods=2)

and then filter your values by date thanks to a map:

df.loc[df['my_date_col'].map(lambda row: row.date() in rge)]

Animate element to auto height with jQuery

this is working and it is simplier then solutions before:

CSS:

#container{
  height:143px;  
}

.max{
  height: auto;
  min-height: 143px;
}

JS:

$(document).ready(function() {
    $("#container").click(function() {      
        if($(this).hasClass("max")) {
            $(this).removeClass("max");
        } else {
            $(this).addClass("max");
        }

    })
});

Note: This solution requires jQuery UI

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Unexpected end of file means that something else was expected before the PHP parser reached the end of the script.

Judging from your HUGE file, it's probably that you're missing a closing brace (}) from an if statement.

Please at least attempt the following things:

  1. Separate your code from your view logic.
  2. Be consistent, you're using an end ; in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?> vs <?php echo $this->layouts->print_includes() ?>. It's not required, so don't use it (or do, just do one or the other).
  3. Repeated because it's important, separate your concerns. There's no need for all of this code.
  4. Use an IDE, it will help you with errors such as this going forward.

How to get out of while loop in java with Scanner method "hasNext" as condition?

it doesn't work because you have not programmed a fail-safe into the code. java sees that the scanner can still collect input while there is input to be collected and if possible, while that is true, it keeps doing so. having a scanner test to see if a certain word, like EXIT for example, is fine, but you could also have it loop a certain number of times, like ten or so. but the most efficient approach is to ask the user of your program how many strings they wish to enter, and while the number of strings they enter is less than the number they put in, the program shall execute. an added option could be if they type EXIT, when they see they need less spaces than they put in and don't want to fill the next cells up with nothing but whitespace. and you could have the program ask if they want to enter more input, in case they realize they need to enter more data into the computer. the program would be quite simplistic to make, as well because there are a plethera of ways you could do it. feel free to ask me for these ways, i'm running out of room though. XD

What do \t and \b do?

\t is the tab character, and is doing exactly what you're anticipating based on the action of \b - it goes to the next tab stop, then gets decremented, and then goes to the next tab stop (which is in this case the same tab stop, because of the \b.

Text size of android design TabLayout tabs

I was using Android Pie and nothing seemed to worked so I played around with app:tabTextAppearance attribute. I know its not the perfect answer but might help someone.

<android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabTextAppearance="@style/TextAppearance.AppCompat.Caption" />

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

The property 'Id' is part of the object's key information and cannot be modified

For me the issue was caused by the lack of a Primary Key to my table, after setting a PK for the table the problem was gone

'Connect-MsolService' is not recognized as the name of a cmdlet

Following worked for me:

  1. Uninstall the previously installed ‘Microsoft Online Service Sign-in Assistant’ and ‘Windows Azure Active Directory Module for Windows PowerShell’.
  2. Install 64-bit versions of ‘Microsoft Online Service Sign-in Assistant’ and ‘Windows Azure Active Directory Module for Windows PowerShell’. https://littletalk.wordpress.com/2013/09/23/install-and-configure-the-office-365-powershell-cmdlets/

If you get the following error In order to install Windows Azure Active Directory Module for Windows PowerShell, you must have Microsoft Online Services Sign-In Assistant version 7.0 or greater installed on this computer, then install the Microsoft Online Services Sign-In Assistant for IT Professionals BETA: http://www.microsoft.com/en-us/download/details.aspx?id=39267

  1. Copy the folders called MSOnline and MSOnline Extended from the source

C:\Windows\System32\WindowsPowerShell\v1.0\Modules\

to the folder

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\Modules\

https://stackoverflow.com/a/16018733/5810078.

(But I have actually copied all the possible files from

C:\Windows\System32\WindowsPowerShell\v1.0\

to

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

(For copying you need to alter the security permissions of that folder))

Python - 'ascii' codec can't decode byte

Always encode from unicode to bytes.
In this direction, you get to choose the encoding.

>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
??

The other way is to decode from bytes to unicode.
In this direction, you have to know what the encoding is.

>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
??
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
??

This point can't be stressed enough. If you want to avoid playing unicode "whack-a-mole", it's important to understand what's happening at the data level. Here it is explained another way:

  • A unicode object is decoded already, you never want to call decode on it.
  • A bytestring object is encoded already, you never want to call encode on it.

Now, on seeing .encode on a byte string, Python 2 first tries to implicitly convert it to text (a unicode object). Similarly, on seeing .decode on a unicode string, Python 2 implicitly tries to convert it to bytes (a str object).

These implicit conversions are why you can get UnicodeDecodeError when you've called encode. It's because encoding usually accepts a parameter of type unicode; when receiving a str parameter, there's an implicit decoding into an object of type unicode before re-encoding it with another encoding. This conversion chooses a default 'ascii' decoder, giving you the decoding error inside an encoder.

In fact, in Python 3 the methods str.decode and bytes.encode don't even exist. Their removal was a [controversial] attempt to avoid this common confusion.

...or whatever coding sys.getdefaultencoding() mentions; usually this is 'ascii'

Where does mysql store data?

In version 5.6 at least, the Management tab in MySQL Workbench shows that it's in a hidden folder called ProgramData in the C:\ drive. My default data directory is

C:\ProgramData\MySQL\MySQL Server 5.6\data

. Each database has a folder and each table has a file here.

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

Download and install an ipa from self hosted url on iOS

Yes, safari will detect the *.ipa and will try to install it, but the ipa needs to be correctly signed and only allowed devices would be able to install it.

http://www.diawi.com is a service that will help you with this process.

All of this is for Ad-hoc distribution, not for production apps.

More information on below link : Is there a way to install iPhone App via browser?

Regex to match 2 digits, optional decimal, two digits

you can use

let regex = new RegExp( ^(?=[0-9.]{1,${maxlength}}$)[0-9]+(?:\.[0-9]{0,${decimal_number}})?$ );

where you can decide the maximum length and up to which decimal point you want to control the value

Use ES6 String interpolation to wrap the variables ${maxlength} and ${decimal_number}.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

I don't have the reputation yet to up vote Steve's suggestion, but it solved my problem.

In my case, I received this error because the two table where created using different database engines--one was Innodb and the other MyISAM.

You can change the database type using : ALTER TABLE t ENGINE = MYISAM;

@see http://dev.mysql.com/doc/refman/5.1/en/storage-engine-setting.html

How to get index using LINQ?

An IEnumerable is not an ordered set.
Although most IEnumerables are ordered, some (such as Dictionary or HashSet) are not.

Therefore, LINQ does not have an IndexOf method.

However, you can write one yourself:

///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate) {
    if (items == null) throw new ArgumentNullException("items");
    if (predicate == null) throw new ArgumentNullException("predicate");

    int retVal = 0;
    foreach (var item in items) {
        if (predicate(item)) return retVal;
        retVal++;
    }
    return -1;
}
///<summary>Finds the index of the first occurrence of an item in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="item">The item to find.</param>
///<returns>The index of the first matching item, or -1 if the item was not found.</returns>
public static int IndexOf<T>(this IEnumerable<T> items, T item) { return items.FindIndex(i => EqualityComparer<T>.Default.Equals(item, i)); }

How to Make A Chevron Arrow Using CSS?

An other approach using borders and no CSS3 properties :

_x000D_
_x000D_
div, div:after{_x000D_
    border-width: 80px 0 80px 80px;_x000D_
    border-color: transparent transparent transparent #000;_x000D_
    border-style:solid;_x000D_
    position:relative;_x000D_
}_x000D_
div:after{_x000D_
    content:'';_x000D_
    position:absolute;_x000D_
    left:-115px; top:-80px;_x000D_
    border-left-color:#fff;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Easy way to dismiss keyboard?

In swift :

self.view.endEditing(true)

What’s the difference between Response.Write() andResponse.Output.Write()?

Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.

Here is example:

protected void Button1_Click(object sender, EventArgs e)
    {
       Response.Write ("hi good morning!"+"is it right?");//only strings are allowed        
       Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
       Response.Output.Write("\nhi goood morning!");//works fine
       Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
    }

What is the most efficient way to create HTML elements using jQuery?

Someone has already made a benchmark: jQuery document.createElement equivalent?

$(document.createElement('div')) is the big winner.

Output in a table format in Java's System.out

Use System.out.format . You can set lengths of fields like this:

System.out.format("%32s%10d%16s", string1, int1, string2);

This pads string1, int1, and string2 to 32, 10, and 16 characters, respectively.

See the Javadocs for java.util.Formatter for more information on the syntax (System.out.format uses a Formatter internally).

How can I record a Video in my Android App.?

Here is another example which is working

public class EnregistrementVideoStackActivity extends Activity implements SurfaceHolder.Callback {
    private SurfaceHolder surfaceHolder;
    private SurfaceView surfaceView;
    public MediaRecorder mrec = new MediaRecorder();
    private Button startRecording = null;

    File video;
    private Camera mCamera;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera_surface);
        Log.i(null , "Video starting");
        startRecording = (Button)findViewById(R.id.buttonstart);
        mCamera = Camera.open();
        surfaceView = (SurfaceView) findViewById(R.id.surface_camera);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        menu.add(0, 0, 0, "StartRecording");
        menu.add(0, 1, 0, "StopRecording");
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
        case 0:
            try {
                startRecording();
            } catch (Exception e) {
                String message = e.getMessage();
                Log.i(null, "Problem Start"+message);
                mrec.release();
            }
            break;

        case 1: //GoToAllNotes
            mrec.stop();
            mrec.release();
            mrec = null;
            break;

        default:
            break;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void startRecording() throws IOException 
    {
        mrec = new MediaRecorder();  // Works well
        mCamera.unlock();

        mrec.setCamera(mCamera);

        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        mrec.setAudioSource(MediaRecorder.AudioSource.MIC); 

        mrec.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));
        mrec.setPreviewDisplay(surfaceHolder.getSurface());
        mrec.setOutputFile("/sdcard/zzzz.3gp"); 

        mrec.prepare();
        mrec.start();
    }

    protected void stopRecording() {
        mrec.stop();
        mrec.release();
        mCamera.release();
    }

    private void releaseMediaRecorder(){
        if (mrec != null) {
            mrec.reset();   // clear recorder configuration
            mrec.release(); // release the recorder object
            mrec = null;
            mCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (mCamera != null){
            mCamera.release();        // release the camera for other applications
            mCamera = null;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (mCamera != null){
            Parameters params = mCamera.getParameters();
            mCamera.setParameters(params);
        }
        else {
            Toast.makeText(getApplicationContext(), "Camera not available!", Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        mCamera.stopPreview();
        mCamera.release();
    }
}

camera_surface.xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<SurfaceView
    android:id="@+id/surface_camera"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1" />

<Button
    android:id="@+id/buttonstart"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/record_start" />

</RelativeLayout>

And of course include these permission in manifest:

<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

File count from a folder

System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("SourcePath");
int count = dir.GetFiles().Length;

You can use this.

How to create a template function within a class? (C++)

Yes, template member functions are perfectly legal and useful on numerous occasions.

The only caveat is that template member functions cannot be virtual.

Show div #id on click with jQuery

This is simple way to Display Div using:-

$("#musicinfo").show();  //or
$("#musicinfo").css({'display':'block'});  //or
$("#musicinfo").toggle("slow");   //or
$("#musicinfo").fadeToggle();    //or

how to get request path with express req object

To supplement, here is an example expanded from the documentation, which nicely wraps all you need to know about accessing the paths/URLs in all cases with express:

app.use('/admin', function (req, res, next) { // GET 'http://www.example.com/admin/new?a=b'
  console.dir(req.originalUrl) // '/admin/new?a=b' (WARNING: beware query string)
  console.dir(req.baseUrl) // '/admin'
  console.dir(req.path) // '/new'
  console.dir(req.baseUrl + req.path) // '/admin/new' (full path without query string)
  next()
})

Based on: https://expressjs.com/en/api.html#req.originalUrl

Conclusion: As c1moore's answer states, use:

var fullPath = req.baseUrl + req.path;

Displaying a vector of strings in C++

Because userString is empty. You only declare it

vector<string> userString;     

but never add anything, so the for loop won't even run.

set font size in jquery

$("#"+styleTarget).css('font-size', newFontSize);

Proper way to assert type of variable in Python

You might want to try this example for version 2.6 of Python.

def my_print(text, begin, end):
    "Print text in UPPER between 'begin' and 'end' in lower."
    for obj in (text, begin, end):
        assert isinstance(obj, str), 'Argument of wrong type!'
    print begin.lower() + text.upper() + end.lower()

However, have you considered letting the function fail naturally instead?

Fast way of finding lines in one file that are not in another?

whats the speed of as sort and diff?

sort file1 -u > file1.sorted
sort file2 -u > file2.sorted
diff file1.sorted file2.sorted

How can I stop python.exe from closing immediately after I get an output?

Just declare a variable like k or m or any other you want, now just add this piece of code at the end of your program

k=input("press close to exit") 

Here I just assumed k as variable to pause the program, you can use any variable you like.

fork() child and parent processes

It is printing the statement twice because it is printing it for both the parent and the child. The parent has a parent id of 0

Try something like this:

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(),getppid());
 else 
    printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), getppid() );

self.tableView.reloadData() not working in Swift

If your connection is in background thread then you should update UI in main thread like this

self.tblMainTable.performSelectorOnMainThread(Selector("reloadData"), withObject: nil, waitUntilDone: true)

As I have mentioned here

Swift 4:

self.tblMainTable.performSelector(onMainThread: #selector(UICollectionView.reloadData), with: nil, waitUntilDone: true)

JavaScript TypeError: Cannot read property 'style' of null

In your script, this part:

document.getElementById('Noite')

must be returning null and you are also attempting to set the display property to an invalid value. There are a couple of possible reasons for this first part to be null.

  1. You are running the script too early before the document has been loaded and thus the Noite item can't be found.

  2. There is no Noite item in your HTML.

I should point out that your use of document.write() in this case code probably signifies a problem. If the document has already loaded, then a new document.write() will clear the old content and start a new fresh document so no Noite item would be found.

If your document has not yet been loaded and thus you're doing document.write() inline to add HTML inline to the current document, then your document has not yet been fully loaded so that's probably why it can't find the Noite item.

The solution is probably to put this part of your script at the very end of your document so everything before it has already been loaded. So move this to the end of your body:

document.getElementById('Noite').style.display='block';

And, make sure that there are no document.write() statements in javascript after the document has been loaded (because they will clear the previous document and start a new one).


In addition, setting the display property to "display" doesn't make sense to me. The valid options for that are "block", "inline", "none", "table", etc... I'm not aware of any option named "display" for that style property. See here for valid options for teh display property.

You can see the fixed code work here in this demo: http://jsfiddle.net/jfriend00/yVJY4/. That jsFiddle is configured to have the javascript placed at the end of the document body so it runs after the document has been loaded.


P.S. I should point out that your lack of braces for your if statements and your inclusion of multiple statements on the same line makes your code very misleading and unclear.


I'm having a really hard time figuring out what you're asking, but here's a cleaned up version of your code that works which you can also see working here: http://jsfiddle.net/jfriend00/QCxwr/. Here's a list of the changes I made:

  1. The script is located in the body, but after the content that it is referencing.
  2. I've added var declarations to your variables (a good habit to always use).
  3. The if statement was changed into an if/else which is a lot more efficient and more self-documenting as to what you're doing.
  4. I've added braces for every if statement so it absolutely clear which statements are part of the if/else and which are not.
  5. I've properly closed the </dd> tag you were inserting.
  6. I've changed style.display = ''; to style.display = 'block';.
  7. I've added semicolons at the end of every statement (another good habit to follow).

The code:

<div id="Night" style="display: none;">
    <img src="Img/night.png" style="position: fixed; top: 0px; left: 5%; height: auto; width: 100%; z-index: -2147483640;">
    <img src="Img/moon.gif" style="position: fixed; top: 0px; left: 5%; height: 100%; width: auto; z-index: -2147483639;">
</div>    
<script>
document.write("<dl><dd>");
var day = new Date();
var hr = day.getHours();
if (hr == 0) {
    document.write("Meia-noite!<br>Já é amanhã!");
} else if (hr <=5 ) {
    document.write("&nbsp;&nbsp;Você não<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;devia<br>&nbsp;&nbsp;&nbsp;&nbsp;estar<br>dormindo?");
} else if (hr <= 11) {         
    document.write("Bom dia!");
} else if (hr == 12) {
    document.write("&nbsp;&nbsp;&nbsp;&nbsp;Vamos<br>&nbsp;almoçar?");
} else if (hr <= 17) {
    document.write("Boa Tarde");
} else if (hr <= 19) {
    document.write("&nbsp;Bom final<br>&nbsp;de tarde!");
} else if (hr == 20) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='block';
} else if (hr == 21) {
    document.write("&nbsp;Boa Noite"); 
    document.getElementById('Noite').style.display='none';
} else if (hr == 22) {
    document.write("&nbsp;Boa Noite");
} else if (hr == 23) {
    document.write("Ó Meu! Já é quase meia-noite!");
}
document.write("</dl></dd>");
</script>

Ctrl+click doesn't work in Eclipse Juno

On my system, Ctrl+click brings up the right-click menu instead of opening the declaration. However, if you hold Ctrl and hover the mouse pointer over the variable/class/method name, a small boxed menu appears with "open declaration" at the top. You can move the pointer down and click that item to get the desired effect.

I'm running Ubuntu 14.04 through VMWare on OS X.

check android application is in foreground or not?

I've found a simple soluition for this by creating a base activity class , u must extend all your activity classes from this :

public class BaseActivity extends ActionBarActivity {

@Override
protected void onResume() {
    ApplicationStateChecker.view_resumed(this);
    super.onResume();
}

@Override
protected void onStop() {
    ApplicationStateChecker.view_stopped(this);
    super.onStop();

}

@Override
protected void onPause() {
    ApplicationStateChecker.view_paused(this);
    super.onPause();

}

}

ApplicationStateChecker class :

public class ApplicationStateChecker {

private  static final String _pause_string = "paused";
private  static final String _resume_string = "resumed";

private static String _view_lastState;
private static boolean _from_background = true;

public static void view_paused(Activity activity){
    _view_lastState = _pause_string;
}

public static void view_stopped(Activity activity){

    if (  _view_lastState.equals(_pause_string) ){
        //if stop called and last event was pause then app is brought to background
        _from_background = true;
    }  //if

}

public static void view_resumed(Activity activity){

    if (  _from_background ) {
       //Do your stuff here , app is brought to foreground 

    }  //if

    _from_background = false;
    _view_lastState = _resume_string;
}

Clearing all cookies with JavaScript

I found a problem in IE and Edge. Webkit browsers (Chrome, safari) seem to be more forgiving. When setting cookies, always set the "path" to something, because the default will be the page that set the cookie. So if you try to expire it on a different page without specifying the "path", the path won't match and it won't expire. The document.cookie value doesn't show the path or expiration for a cookie, so you can't derive where the cookie was set by looking at the value.

If you need to expire cookies from different pages, save the path of the setting page in the cookie value so you can pull it out later or always append "; path=/;" to the cookie value. Then it will expire from any page.

Maven Run Project

clean package exec:java -P Class_Containing_Main_Method command is also an option if you have only one Main method(PSVM) in the project, with the following Maven Setup.

Don't forget to mention the class in the <properties></properties> section of pom.xml :

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.main.class>com.test.service.MainTester</java.main.class>
</properties>

<plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>exec-maven-plugin</artifactId>
        <version>1.2.1</version>
        <configuration>
           <mainClass>${java.main.class}</mainClass>
        </configuration>
</plugin>

STS Run Configuration along with above Maven Setup:

enter image description here

How to get the list of all database users

Go for this:

 SELECT name,type_desc FROM sys.sql_logins

concat yesterdays date with a specific time

where date_dt = to_date(to_char(sysdate-1, 'YYYY-MM-DD') || ' 19:16:08', 'YYYY-MM-DD HH24:MI:SS') 

should work.

Strip first and last character from C string

Further to @pmg's answer, note that you can do both operations in one statement:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;

This will likely work as expected but behavior is undefined in C standard.

store and retrieve a class object in shared preference

Do you need to retrieve the object even after the application shutting donw or just during it's running ?

You can store it into a database.
Or Simply create a custom Application class.

public class MyApplication extends Application {

    private static Object mMyObject;
    // static getter & setter
    ...
}

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application ... android:name=".MyApplication">
        <activity ... />
        ...
    </application>
    ...
</manifest>

And then from every activities do :

((MyApplication) getApplication).getMyObject();

Not really the best way but it works.

How to replace multiple white spaces with one white space

There is no way built in to do this. You can try this:

private static readonly char[] whitespace = new char[] { ' ', '\n', '\t', '\r', '\f', '\v' };
public static string Normalize(string source)
{
   return String.Join(" ", source.Split(whitespace, StringSplitOptions.RemoveEmptyEntries));
}

This will remove leading and trailing whitespce as well as collapse any internal whitespace to a single whitespace character. If you really only want to collapse spaces, then the solutions using a regular expression are better; otherwise this solution is better. (See the analysis done by Jon Skeet.)

How to check a boolean condition in EL?

You can have a look at the EL (expression language) description here.

Both your code are correct, but I prefer the second one, as comparing a boolean to true or false is redundant.

For better readibility, you can also use the not operator:

<c:if test="${not theBooleanVariable}">It's false!</c:if>

ldconfig error: is not a symbolic link

simple run in shell : sudo apt-get install --reinstall libexpat1
got same problem with libxcb - solved in this way - very fast :)

change cursor to finger pointer

Add an href attribute to make it a valid link & return false; in the event handler to prevent it from causing a navigation;

<a href="#" class="menu_links" onclick="displayData(11,1,0,'A'); return false;" onmouseover=""> A </a>

(Or make displayData() return false and ..="return displayData(..)

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

SVN commit command

To add a file/folder to the project, a good way is:

First of all add your files to /path/to/your/project/my/added/files, and then run following commands:

svn cleanup  /path/to/your/project

svn add --force /path/to/your/project/*

svn cleanup  /path/to/your/project

svn commit /path/to/your/project  -m 'Adding a file'

I used cleanup to prevent any segmentation fault (core dumped), and now the SVN project is updated.

Java Thread Example?

Here is a simple example:

ThreadTest.java

public class ThreadTest
{
   public static void main(String [] args)
   {
      MyThread t1 = new MyThread(0, 3, 300);
      MyThread t2 = new MyThread(1, 3, 300);
      MyThread t3 = new MyThread(2, 3, 300);

      t1.start();
      t2.start();
      t3.start();
   }
}

MyThread.java

public class MyThread extends Thread
{
   private int startIdx, nThreads, maxIdx;

   public MyThread(int s, int n, int m)
   {
      this.startIdx = s;
      this.nThreads = n;
      this.maxIdx = m;
   }

   @Override
   public void run()
   {
      for(int i = this.startIdx; i < this.maxIdx; i += this.nThreads)
      {
         System.out.println("[ID " + this.getId() + "] " + i);
      }
   }
}

And some output:

[ID 9] 1
[ID 10] 2
[ID 8] 0
[ID 10] 5
[ID 9] 4
[ID 10] 8
[ID 8] 3
[ID 10] 11
[ID 10] 14
[ID 10] 17
[ID 10] 20
[ID 10] 23

An explanation - Each MyThread object tries to print numbers from 0 to 300, but they are only responsible for certain regions of that range. I chose to split it by indices, with each thread jumping ahead by the number of threads total. So t1 does index 0, 3, 6, 9, etc.

Now, without IO, trivial calculations like this can still look like threads are executing sequentially, which is why I just showed the first part of the output. On my computer, after this output thread with ID 10 finishes all at once, followed by 9, then 8. If you put in a wait or a yield, you can see it better:

MyThread.java

System.out.println("[ID " + this.getId() + "] " + i);
Thread.yield();

And the output:

[ID 8] 0
[ID 9] 1
[ID 10] 2
[ID 8] 3
[ID 9] 4
[ID 8] 6
[ID 10] 5
[ID 9] 7

Now you can see each thread executing, giving up control early, and the next executing.

HTTP Request in Kotlin

For Android, Volley is a good place to get started. For all platforms, you might also want to check out ktor client or http4k which are both good libraries.

However, you can also use standard Java libraries like java.net.HttpURLConnection which is part of the Java SDK:

fun sendGet() {
    val url = URL("http://www.google.com/")

    with(url.openConnection() as HttpURLConnection) {
        requestMethod = "GET"  // optional default is GET

        println("\nSent 'GET' request to URL : $url; Response Code : $responseCode")

        inputStream.bufferedReader().use {
            it.lines().forEach { line ->
                println(line)
            }
        }
    }
}

Or simpler:

URL("https://google.com").readText()

How to read a configuration file in Java

It depends.

Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding

And if none of those meet your particular needs, you could even look at using some kind of Database

What is the easiest way to parse an INI File in C++?

If you need a cross-platform solution, try Boost's Program Options library.

Creating a "logical exclusive or" operator in Java

What you're asking for wouldn't make much sense. Unless I'm incorrect you're suggesting that you want to use XOR to perform Logical operations the same way AND and OR do. Your provided code actually shows what I'm reffering to:

public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}

Your function has boolean inputs, and when bitwise XOR is used on booleans the result is the same as the code you've provided. In other words, bitwise XOR is already efficient when comparing individual bits(booleans) or comparing the individual bits in larger values. To put this into context, in terms of binary values any non-zero value is TRUE and only ZERO is false.

So for XOR to be applied the same way Logical AND is applied, you would either only use binary values with just one bit(giving the same result and efficiency) or the binary value would have to be evaluated as a whole instead of per bit. In other words the expression ( 010 ^^ 110 ) = FALSE instead of ( 010 ^^ 110 ) = 100. This would remove most of the semantic meaning from the operation, and represents a logical test you shouldn't be using anyway.

How to calculate the inverse of the normal cumulative distribution function in python?

# given random variable X (house price) with population muy = 60, sigma = 40
import scipy as sc
import scipy.stats as sct
sc.version.full_version # 0.15.1

#a. Find P(X<50)
sct.norm.cdf(x=50,loc=60,scale=40) # 0.4012936743170763

#b. Find P(X>=50)
sct.norm.sf(x=50,loc=60,scale=40) # 0.5987063256829237

#c. Find P(60<=X<=80)
sct.norm.cdf(x=80,loc=60,scale=40) - sct.norm.cdf(x=60,loc=60,scale=40)

#d. how much top most 5% expensive house cost at least? or find x where P(X>=x) = 0.05
sct.norm.isf(q=0.05,loc=60,scale=40)

#e. how much top most 5% cheapest house cost at least? or find x where P(X<=x) = 0.05
sct.norm.ppf(q=0.05,loc=60,scale=40)

Where is Python's sys.path initialized from?

Python really tries hard to intelligently set sys.path. How it is set can get really complicated. The following guide is a watered-down, somewhat-incomplete, somewhat-wrong, but hopefully-useful guide for the rank-and-file python programmer of what happens when python figures out what to use as the initial values of sys.path, sys.executable, sys.exec_prefix, and sys.prefix on a normal python installation.

First, python does its level best to figure out its actual physical location on the filesystem based on what the operating system tells it. If the OS just says "python" is running, it finds itself in $PATH. It resolves any symbolic links. Once it has done this, the path of the executable that it finds is used as the value for sys.executable, no ifs, ands, or buts.

Next, it determines the initial values for sys.exec_prefix and sys.prefix.

If there is a file called pyvenv.cfg in the same directory as sys.executable or one directory up, python looks at it. Different OSes do different things with this file.

One of the values in this config file that python looks for is the configuration option home = <DIRECTORY>. Python will use this directory instead of the directory containing sys.executable when it dynamically sets the initial value of sys.prefix later. If the applocal = true setting appears in the pyvenv.cfg file on Windows, but not the home = <DIRECTORY> setting, then sys.prefix will be set to the directory containing sys.executable.

Next, the PYTHONHOME environment variable is examined. On Linux and Mac, sys.prefix and sys.exec_prefix are set to the PYTHONHOME environment variable, if it exists, superseding any home = <DIRECTORY> setting in pyvenv.cfg. On Windows, sys.prefix and sys.exec_prefix is set to the PYTHONHOME environment variable, if it exists, unless a home = <DIRECTORY> setting is present in pyvenv.cfg, which is used instead.

Otherwise, these sys.prefix and sys.exec_prefix are found by walking backwards from the location of sys.executable, or the home directory given by pyvenv.cfg if any.

If the file lib/python<version>/dyn-load is found in that directory or any of its parent directories, that directory is set to be to be sys.exec_prefix on Linux or Mac. If the file lib/python<version>/os.py is is found in the directory or any of its subdirectories, that directory is set to be sys.prefix on Linux, Mac, and Windows, with sys.exec_prefix set to the same value as sys.prefix on Windows. This entire step is skipped on Windows if applocal = true is set. Either the directory of sys.executable is used or, if home is set in pyvenv.cfg, that is used instead for the initial value of sys.prefix.

If it can't find these "landmark" files or sys.prefix hasn't been found yet, then python sets sys.prefix to a "fallback" value. Linux and Mac, for example, use pre-compiled defaults as the values of sys.prefix and sys.exec_prefix. Windows waits until sys.path is fully figured out to set a fallback value for sys.prefix.

Then, (what you've all been waiting for,) python determines the initial values that are to be contained in sys.path.

  1. The directory of the script which python is executing is added to sys.path. On Windows, this is always the empty string, which tells python to use the full path where the script is located instead.
  2. The contents of PYTHONPATH environment variable, if set, is added to sys.path, unless you're on Windows and applocal is set to true in pyvenv.cfg.
  3. The zip file path, which is <prefix>/lib/python35.zip on Linux/Mac and os.path.join(os.dirname(sys.executable), "python.zip") on Windows, is added to sys.path.
  4. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  5. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  6. If on Windows and no applocal = true was set in pyvenv.cfg, then the contents of the subkeys of the registry key HK_LOCAL_MACHINE\Software\Python\PythonCore\<DLLVersion>\PythonPath\ are added, if any.
  7. If on Windows and no applocal = true was set in pyvenv.cfg, and sys.prefix could not be found, then the core contents of the of the registry key HK_CURRENT_USER\Software\Python\PythonCore\<DLLVersion>\PythonPath\ is added, if it exists;
  8. If on Windows, and PYTHONPATH was not set, the prefix was not found, and no registry keys were present, then the relative compile-time value of PYTHONPATH is added; otherwise, this step is ignored.
  9. Paths in the compile-time macro PYTHONPATH are added relative to the dynamically-found sys.prefix.
  10. On Mac and Linux, the value of sys.exec_prefix is added. On Windows, the directory which was used (or would have been used) to search dynamically for sys.prefix is added.

At this stage on Windows, if no prefix was found, then python will try to determine it by searching all the directories in sys.path for the landmark files, as it tried to do with the directory of sys.executable previously, until it finds something. If it doesn't, sys.prefix is left blank.

Finally, after all this, Python loads the site module, which adds stuff yet further to sys.path:

It starts by constructing up to four directories from a head and a tail part. For the head part, it uses sys.prefix and sys.exec_prefix; empty heads are skipped. For the tail part, it uses the empty string and then lib/site-packages (on Windows) or lib/pythonX.Y/site-packages and then lib/site-python (on Unix and Macintosh). For each of the distinct head-tail combinations, it sees if it refers to an existing directory, and if so, adds it to sys.path and also inspects the newly added path for configuration files.

Find the min/max element of an array in JavaScript

For an array containing objects instead of numbers:

arr = [
  { name: 'a', value: 5 },
  { name: 'b', value: 3 },
  { name: 'c', value: 4 }
]

You can use reduce to get the element with the smallest value (min)

arr.reduce((a, b) => a.value < b.value ? a : b)
// { name: 'b', value: 3 }

or the largest value (max)

arr.reduce((a, b) => a.value > b.value ? a : b)
// { name: 'a', value: 5 }

Linq select objects in list where exists IN (A,B,C)

NB: this is LINQ to objects, I am not 100% sure if it work in LINQ to entities, and have no time to check it right now. In fact it isn't too difficult to translate it to x in [A, B, C] but you have to check for yourself.

So, instead of Contains as a replacement of the ???? in your code you can use Any which is more LINQ-uish:

// Filter the orders based on the order status
var filteredOrders = from order in orders.Order
                     where new[] { "A", "B", "C" }.Any(s => s == order.StatusCode)
                     select order;

It's the opposite to what you know from SQL this is why it is not so obvious.

Of course, if you prefer fluent syntax here it is:

var filteredOrders = orders.Order.Where(order => new[] {"A", "B", "C"}.Any(s => s == order.StatusCode));

Here we again see one of the LINQ surprises (like Joda-speech which puts select at the end). However it is quite logical in this sense that it checks if at least one of the items (that is any) in a list (set, collection) matches a single value.

Remove sensitive files and their commits from Git history

You can use git forget-blob.

The usage is pretty simple git forget-blob file-to-forget. You can get more info here

https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/

It will disappear from all the commits in your history, reflog, tags and so on

I run into the same problem every now and then, and everytime I have to come back to this post and others, that's why I automated the process.

Credits to contributors from Stack Overflow that allowed me to put this together

Sending event when AngularJS finished loading

may be i can help you by this example

In the custom fancybox I show contents with interpolated values.

in the service, in the "open" fancybox method, i do

open: function(html, $compile) {
        var el = angular.element(html);
     var compiledEl = $compile(el);
        $.fancybox.open(el); 
      }

the $compile returns compiled data. you can check the compiled data

How to know what the 'errno' means?

Here is the documentation. That should tell you what it means and what to do with them. You should avoid using the numeric value and use the constants listed there as well, as the number may change between different systems.

Declaring static constants in ES6 classes?

In this document it states:

There is (intentionally) no direct declarative way to define either prototype data properties (other than methods) class properties, or instance property

This means that it is intentionally like this.

Maybe you can define a variable in the constructor?

constructor(){
    this.key = value
}

How to clamp an integer to some range?

Avoid writing functions for such small tasks, unless you apply them often, as it will clutter up your code.

for individual values:

min(clamp_max, max(clamp_min, value))

for lists of values:

map(lambda x: min(clamp_max, max(clamp_min, x)), values)

Error Running React Native App From Terminal (iOS)

In my case the problem was that Xcode was not installed.

Convert timestamp to readable date/time PHP

If you are using PHP date(), you can use this code to get the date, time, second, etc.

$time = time();               // you have 1299446702 in time
$year = $time/31556926 % 12;  // to get year
$week = $time / 604800 % 52;  // to get weeks
$hour = $time / 3600 % 24;    // to get hours
$minute = $time / 60 % 60;    // to get minutes
$second = $time % 60;         // to get seconds

How to select a drop-down menu value with Selenium using Python?

The best way to use selenium.webdriver.support.ui.Select class to work to with dropdown selection but some time it does not work as expected due to designing issue or other issues of the HTML.

In this type of situation you can also prefer as alternate solution using execute_script() as below :-

option_visible_text = "Banana"
select = driver.find_element_by_id("fruits01")

#now use this to select option from dropdown by visible text 
driver.execute_script("var select = arguments[0]; for(var i = 0; i < select.options.length; i++){ if(select.options[i].text == arguments[1]){ select.options[i].selected = true; } }", select, option_visible_text);

Reference requirements.txt for the install_requires kwarg in setuptools setup.py file

I would not recommend doing such a thing. As mentioned multiple times install_requires and requirements.txt are definitely not supposed to be the same list. But since there are a lot of misleading answers all around involving private internal APIs of pip, it might be worth looking at saner alternatives...

There is no need for pip to parse a requirements.txt file from a setuptools setup.py script. The setuptools project already contains all the necessary tools in its top level package pkg_resources.

It could more or less look like this:

#!/usr/bin/env python3

import pathlib

import pkg_resources
import setuptools

with pathlib.Path('requirements.txt').open() as requirements_txt:
    install_requires = [
        str(requirement)
        for requirement
        in pkg_resources.parse_requirements(requirements_txt)
    ]

setuptools.setup(
    install_requires=install_requires,
)

Notes:

C#: How would I get the current time into a string?

You can use format strings as well.

string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros

or some shortcuts if the format works for you

string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();

Either should work.

jQuery .on('change', function() {} not triggering for dynamically created inputs

Use this

$('body').on('change', '#id', function() {
  // Action goes here.
});

What is the use of verbose in Keras while validating the model?

By default verbose = 1,

verbose = 1, which includes both progress bar and one line per epoch

verbose = 0, means silent

verbose = 2, one line per epoch i.e. epoch no./total no. of epochs

PHP equivalent of .NET/Java's toString()

I think this question is a bit misleading since, toString() in Java isn't just a way to cast something to a String. That is what casting via (string) or String.valueOf() does, and it works as well in PHP.

// Java
String myText = (string) myVar;

// PHP
$myText = (string) $myVar;

Note that this can be problematic as Java is type-safe (see here for more details).

But as I said, this is casting and therefore not the equivalent of Java's toString().

toString in Java doesn't just cast an object to a String. It instead will give you the String representation. And that's what __toString() in PHP does.

// Java
class SomeClass{
    public String toString(){
        return "some string representation";
    }
}

// PHP
class SomeClass{
    public function __toString()
    {
        return "some string representation";
    }
}

And from the other side:

// Java
new SomeClass().toString(); // "Some string representation"

// PHP
strval(new SomeClass); // "Some string representation"

What do I mean by "giving the String representation"? Imagine a class for a library with millions of books.

  • Casting that class to a String would (by default) convert the data, here all books, into a string so the String would be very long and most of the time not very useful either.
  • To String instead will give you the String representation, i.e., only the name of the library. This is shorter and therefore gives you less, but more important information.

These are both valid approaches but with very different goals, neither is a perfect solution for every case and you have to chose wisely which fits better for your needs.

Sure, there are even more options:

$no = 421337  // A number in PHP
$str = "$no"; // In PHP, stuff inside "" is calculated and variables are replaced
$str = print_r($no, true); // Same as String.format();
$str = settype($no, 'string'); // Sets $no to the String Type
$str = strval($no); // Get the string value of $no
$str = $no . ''; // As you said concatenate an empty string works too

All of these methods will return a String, some of them using __toString internally and some others will fail on Objects. Take a look at the PHP documentation for more details.

Bootstrap 3 Carousel Not Working

There are just two minor things here.

The first is in the following carousel indicator list items:

<li data-target="carousel" data-slide-to="0"></li>

You need to pass the data-target attribute a selector which means the ID must be prefixed with #. So change them to the following:

<li data-target="#carousel" data-slide-to="0"></li>

Secondly, you need to give the carousel a starting point so both the carousel indicator items and the carousel inner items must have one active class. Like this:

<ol class="carousel-indicators">
    <li data-target="#carousel" data-slide-to="0" class="active"></li>
    <!-- Other Items -->
</ol>
<div class="carousel-inner">
    <div class="item active">
        <img src="https://picsum.photos/1500/600?image=1" alt="Slide 1" />
    </div>
    <!-- Other Items -->
</div>

Working Demo in Fiddle

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

I tried all the solutions here, but only this parameter

innodb_strict_mode             = 0

solved my day...

From the manual:

The innodb_strict_mode setting affects the handling of syntax errors for CREATE TABLE, ALTER TABLE and CREATE INDEX statements. innodb_strict_mode also enables a record size check, so that an INSERT or UPDATE never fails due to the record being too large for the selected page size.

How to round the double value to 2 decimal points?

public static double addDoubles(double a, double b) {
        BigDecimal A = new BigDecimal(a + "");
        BigDecimal B = new BigDecimal(b + "");
        return A.add(B).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

Open youtube video in Fancybox jquery

This has a regular expression so it's easier to just copy and paste the youtube url. Is great for when you use a CMS for clients.

/*fancybox yt video*/
$(".fancybox-video").click(function() {
    $.fancybox({

    padding: 0,
        'autoScale'     : false,
        'transitionIn'  : 'none',
        'transitionOut' : 'none',
        'title'         : this.title,
        'width'         : 795,
        'height'        : 447,
        'href'          : this.href.replace(new RegExp("watch.*v=","i"), "v/"),
        'type'          : 'swf',
        'swf'           : {
        'wmode'             : 'transparent',
        'allowfullscreen'   : 'true'
         }

    });
    return false;
});

How to copy a dictionary and only edit the copy

In addition to the other provided solutions, you can use ** to integrate the dictionary into an empty dictionary, e.g.,

shallow_copy_of_other_dict = {**other_dict}.

Now you will have a "shallow" copy of other_dict.

Applied to your example:

>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = {**dict1}
>>> dict2
{'key1': 'value1', 'key2': 'value2'}
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key1': 'value1', 'key2': 'value2'}
>>>

Pointer: Difference between shallow and deep copys

Can't get value of input type="file"?

$('input[type=file]').val()

That'll get you the file selected.

However, you can't set the value yourself.

Struct like objects in Java

If the Java way is the OO way, then yes, creating a class with public fields breaks the principles around information hiding which say that an object should manage its own internal state. (So as I'm not just spouting jargon at you, a benefit of information hiding is that the internal workings of a class are hidden behind an interface - say you wanted to change the mechanism by which your struct class saved one of its fields, you'll probably need to go back and change any classes that use the class...)

You also can't take advantage of the support for JavaBean naming compliant classes, which will hurt if you decide to, say, use the class in a JavaServer Page which is written using Expression Language.

The JavaWorld article Why Getter and Setter Methods are Evil article also might be of interest to you in thinking about when not to implement accessor and mutator methods.

If you're writing a small solution and want to minimise the amount of code involved, the Java way may not be the right way - I guess it always depends on you and the problem you're trying to solve.

Send value of submit button when form gets posted

The button names are not submit, so the php $_POST['submit'] value is not set. As in isset($_POST['submit']) evaluates to false.

<html>
<form action="" method="post">
    <input type="hidden" name="action" value="submit" />
    <select name="name">
        <option>John</option>
        <option>Henry</option>
    <select>
<!-- 
make sure all html elements that have an ID are unique and name the buttons submit 
-->
    <input id="tea-submit" type="submit" name="submit" value="Tea">
    <input id="coffee-submit" type="submit" name="submit" value="Coffee">
</form>
</html>

<?php
if (isset($_POST['action'])) {
    echo '<br />The ' . $_POST['submit'] . ' submit button was pressed<br />';
}
?>

Environ Function code samples for VBA

Environ() gets you the value of any environment variable. These can be found by doing the following command in the Command Prompt:

set

If you wanted to get the username, you would do:

Environ("username")

If you wanted to get the fully qualified name, you would do:

Environ("userdomain") & "\" & Environ("username")

References

Count number of occurences for each unique value

It is a one-line approach by using aggregate.

> aggregate(data.frame(count = v), list(value = v), length)

  value count
1     1    25
2     2    75

What's the best way to validate an XML file against an XSD file?

With JAXB, you could use the code below:

    @Test
public void testCheckXmlIsValidAgainstSchema() {
    logger.info("Validating an XML file against the latest schema...");

    MyValidationEventCollector vec = new MyValidationEventCollector();

    validateXmlAgainstSchema(vec, inputXmlFileName, inputXmlSchemaName, inputXmlRootClass);

    assertThat(vec.getValidationErrors().isEmpty(), is(expectedValidationResult));
}

private void validateXmlAgainstSchema(final MyValidationEventCollector vec, final String xmlFileName, final String xsdSchemaName, final Class<?> rootClass) {
    try (InputStream xmlFileIs = Thread.currentThread().getContextClassLoader().getResourceAsStream(xmlFileName);) {
        final JAXBContext jContext = JAXBContext.newInstance(rootClass);
        // Unmarshal the data from InputStream
        final Unmarshaller unmarshaller = jContext.createUnmarshaller();

        final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        final InputStream schemaAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(xsdSchemaName);
        unmarshaller.setSchema(sf.newSchema(new StreamSource(schemaAsStream)));

        unmarshaller.setEventHandler(vec);

        unmarshaller.unmarshal(new StreamSource(xmlFileIs), rootClass).getValue(); // The Document class is the root object in the XML file you want to validate

        for (String validationError : vec.getValidationErrors()) {
            logger.trace(validationError);
        }
    } catch (final Exception e) {
        logger.error("The validation of the XML file " + xmlFileName + " failed: ", e);
    }
}

class MyValidationEventCollector implements ValidationEventHandler {
    private final List<String> validationErrors;

    public MyValidationEventCollector() {
        validationErrors = new ArrayList<>();
    }

    public List<String> getValidationErrors() {
        return Collections.unmodifiableList(validationErrors);
    }

    @Override
    public boolean handleEvent(final ValidationEvent event) {
        String pattern = "line {0}, column {1}, error message {2}";
        String errorMessage = MessageFormat.format(pattern, event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),
                event.getMessage());
        if (event.getSeverity() == ValidationEvent.FATAL_ERROR) {
            validationErrors.add(errorMessage);
        }
        return true; // you collect the validation errors in a List and handle them later
    }
}

What is FCM token in Firebase?

FirebaseInstanceIdService is now deprecated. you should get the Token in the onNewToken method in the FirebaseMessagingService.

Check out the docs

How to push to History in React Router v4?

step one wrap your app in Router

import { BrowserRouter as Router } from "react-router-dom";
ReactDOM.render(<Router><App /></Router>, document.getElementById('root'));

Now my entire App will have access to BrowserRouter. Step two I import Route and then pass down those props. Probably in one of your main files.

import { Route } from "react-router-dom";

//lots of code here

//somewhere in my render function

    <Route
      exact
      path="/" //put what your file path is here
      render={props => (
      <div>
        <NameOfComponent
          {...props} //this will pass down your match, history, location objects
        />
      </div>
      )}
    />

Now if I run console.log(this.props) in my component js file that I should get something that looks like this

{match: {…}, location: {…}, history: {…}, //other stuff }

Step 2 I can access the history object to change my location

//lots of code here relating to my whatever request I just ran delete, put so on

this.props.history.push("/") // then put in whatever url you want to go to

Also I'm just a coding bootcamp student, so I'm no expert, but I know you can also you use

window.location = "/" //wherever you want to go

Correct me if I'm wrong, but when I tested that out it reloaded the entire page which I thought defeated the entire point of using React.

Credentials for the SQL Server Agent service are invalid

the button 'Use same account' below thee main window will fill in all the textboxes automatically. this worked fpr me.

Should import statements always be at the top of a module?

Putting the import statement inside of a function can prevent circular dependencies. For example, if you have 2 modules, X.py and Y.py, and they both need to import each other, this will cause a circular dependency when you import one of the modules causing an infinite loop. If you move the import statement in one of the modules then it won't try to import the other module till the function is called, and that module will already be imported, so no infinite loop. Read here for more - effbot.org/zone/import-confusion.htm

trigger body click with jQuery

Interestingly, when I replaced this:

$("body").trigger("click")

With this:

jQuery("body").trigger("click")

It works!

Php header location redirect not working

Use @obstart or try to use Java Script

put your obstart(); into your top of the page

if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
{
    header('Location: page1.php');
    exit();
}

If you use Javascript Use window.location.href

window.location.href example:

 if ((isset($_POST['cancel'])) && ($_POST['cancel'] == 'cancel'))
    {
        echo "<script type='text/javascript'>window.location.href = 'page1.php';</script>"
        exit();
    }

Bootstrap 4 align navbar items to the right

If all above fails, I added 100% width to the navbar class in CSS. Until then mr auto wasn't working for me on this project using 4.1.

How to pass boolean values to a PowerShell script from a command prompt

A more clear usage might be to use switch parameters instead. Then, just the existence of the Unify parameter would mean it was set.

Like so:

param (
  [int] $Turn,
  [switch] $Unify
)

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

How to set locale in DatePipe in Angular 2?

Ok, I propose this solution, very simple, using ngx-translate

import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';

@Pipe({
  name: 'localizedDate',
  pure: false
})
export class LocalizedDatePipe implements PipeTransform {

  constructor(private translateService: TranslateService) {
}

  transform(value: any): any {
    const date = new Date(value);

    const options = { weekday: 'long',
                  year: 'numeric',
                  month: 'long',
                  day: 'numeric',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit'
                    };

    return date.toLocaleString(this.translateService.currentLang, options);
  }

}

Assign JavaScript variable to Java Variable in JSP

JavaScript is fired on client side and JSP is on server-side. So I can say that it is impossible.

How to add line breaks to an HTML textarea?

If you just need to send the value of the testarea to server with line breaks use nl2br

Excel VBA Loop on columns

Another method to try out. Also select could be replaced when you set the initial column into a Range object. Performance wise it helps.

Dim rng as Range

Set rng = WorkSheets(1).Range("A1") '-- you may change the sheet name according to yours.

'-- here is your loop
i = 1
Do
   '-- do something: e.g. show the address of the column that you are currently in
   Msgbox rng.offset(0,i).Address 
   i = i + 1
Loop Until i > 10

** Two methods to get the column name using column number**

  • Split()

code

colName = Split(Range.Offset(0,i).Address, "$")(1)
  • String manipulation:

code

Function myColName(colNum as Long) as String
    myColName = Left(Range(0, colNum).Address(False, False), _ 
    1 - (colNum > 10)) 
End Function 

How do I call an Angular.js filter with multiple arguments?

i mentioned in the below where i have mentioned the custom filter also , how to call these filter which is having two parameters

countryApp.filter('reverse', function() {
    return function(input, uppercase) {
        var out = '';
        for (var i = 0; i < input.length; i++) {
            out = input.charAt(i) + out;
        }
        if (uppercase) {
            out = out.toUpperCase();
        }
        return out;
    }
});

and from the html using the template we can call that filter like below

<h1>{{inputString| reverse:true }}</h1>

here if you see , the first parameter is inputString and second parameter is true which is combined with "reverse' using the : symbol

What steps are needed to stream RTSP from FFmpeg?

An alternative that I used instead of FFServer was Red5 Pro, on Ubuntu, I used this line: ffmpeg -f pulse -i default -f video4linux2 -thread_queue_size 64 -framerate 25 -video_size 640x480 -i /dev/video0 -pix_fmt yuv420p -bsf:v h264_mp4toannexb -profile:v baseline -level:v 3.2 -c:v libx264 -x264-params keyint=120:scenecut=0 -c:a aac -b:a 128k -ar 44100 -f rtsp -muxdelay 0.1 rtsp://localhost:8554/live/paul

How are booleans formatted in Strings in Python?

You may also use the Formatter class of string

print "{0} {1}".format(True, False);
print "{0:} {1:}".format(True, False);
print "{0:d} {1:d}".format(True, False);
print "{0:f} {1:f}".format(True, False);
print "{0:e} {1:e}".format(True, False);

These are the results

True False
True False
1 0
1.000000 0.000000
1.000000e+00 0.000000e+00

Some of the %-format type specifiers (%r, %i) are not available. For details see the Format Specification Mini-Language

SQL Server stored procedure Nullable parameter

It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.

Other than that, I would suggest two things...

First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...

    ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0

Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.

Print all but the first three columns

I've found this other possibility, maybe it could be useful also...

awk 'BEGIN {OFS=ORS="\t" }; {for(i=1; i<14; i++) print $i " "; print $NF "\n" }' your_file

Note: 1. For tabular data and from column $1 to $14

SQL Server Linked Server Example Query

If you still find issue with <server>.<database>.<schema>.<table>

Enclose server name in []

Insert entire DataTable into database at once instead of row by row?

I would prefer user defined data type : it is super fast.

Step 1 : Create User Defined Table in Sql Server DB

CREATE TYPE [dbo].[udtProduct] AS TABLE(
  [ProductID] [int] NULL,
  [ProductName] [varchar](50) NULL,
  [ProductCode] [varchar](10) NULL
)
GO

Step 2 : Create Stored Procedure with User Defined Type

CREATE PROCEDURE ProductBulkInsertion 
@product udtProduct readonly
AS
BEGIN
    INSERT INTO Product
    (ProductID,ProductName,ProductCode)
    SELECT ProductID,ProductName,ProductCode
    FROM @product
END

Step 3 : Execute Stored Procedure from c#

SqlCommand sqlcmd = new SqlCommand("ProductBulkInsertion", sqlcon);
sqlcmd.CommandType = CommandType.StoredProcedure;
sqlcmd.Parameters.AddWithValue("@product", productTable);
sqlcmd.ExecuteNonQuery();

Possible Issue : Alter User Defined Table

Actually there is no sql server command to alter user defined type But in management studio you can achieve this from following steps

1.generate script for the type.(in new query window or as a file) 2.delete user defied table. 3.modify the create script and then execute.

What exactly does big ? notation represent?

Big Theta notation:

Nothing to mess up buddy!!

If we have a positive valued functions f(n) and g(n) takes a positive valued argument n then ?(g(n)) defined as {f(n):there exist constants c1,c2 and n1 for all n>=n1}

where c1 g(n)<=f(n)<=c2 g(n)

Let's take an example:

let f(n)=

g(n)=

c1=5 and c2=8 and n1=1

Among all the notations ,? notation gives the best intuition about the rate of growth of function because it gives us a tight bound unlike big-oh and big -omega which gives the upper and lower bounds respectively.

? tells us that g(n) is as close as f(n),rate of growth of g(n) is as close to the rate of growth of f(n) as possible.

see the image to get a better intuition

Copy table without copying data

SHOW CREATE TABLE bar;

you will get a create statement for that table, edit the table name, or anything else you like, and then execute it.

This will allow you to copy the indexes and also manually tweak the table creation.

You can also run the query within a program.

How to get table list in database, using MS SQL 2008?

This query will get you all the tables in the database

USE [DatabaseName];

SELECT * FROM information_schema.tables;

Is there a way to create key-value pairs in Bash script?

If you can use a simple delimiter, a very simple oneliner is this:

for i in a,b c_s,d ; do 
  KEY=${i%,*};
  VAL=${i#*,};
  echo $KEY" XX "$VAL;
done

Hereby i is filled with character sequences like "a,b" and "c_s,d". each separated by spaces. After the do we use parameter substitution to extract the part before the comma , and the part after it.

Converting a Java Keystore into PEM Format

Try Keystore Explorer http://keystore-explorer.org/

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. It does openssl/pkcs12 as well.

Updating address bar with new URL without hash or reloading the page

var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?foo=bar';
window.history.pushState({path:newurl},'',newurl);

Playing Sound In Hidden Tag

_x000D_
_x000D_
audio { display:none;}
_x000D_
<audio autoplay="true" src="https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg">
_x000D_
_x000D_
_x000D_

End of File (EOF) in C

EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.

The code isn't wrong[*], it just doesn't do what you seem to expect. It reads to the end of the input, but you seem to want to read only to the end of a line.

The value of EOF is -1 because it has to be different from any return value from getchar that is an actual character. So getchar returns any character value as an unsigned char, converted to int, which will therefore be non-negative.

If you're typing at the terminal and you want to provoke an end-of-file, use CTRL-D (unix-style systems) or CTRL-Z (Windows). Then after all the input has been read, getchar() will return EOF, and hence getchar() != EOF will be false, and the loop will terminate.

[*] well, it has undefined behavior if the input is more than LONG_MAX characters due to integer overflow, but we can probably forgive that in a simple example.

Best way to format integer as string with leading zeros?

You most likely just need to format your integer:

'%0*d' % (fill, your_int)

For example,

>>> '%0*d' % (3, 4)
'004'

How can I give an imageview click effect like a button on Android?

You can do this with a single image using something like this:

     //get the image view
    ImageView imageView = (ImageView)findViewById(R.id.ImageView);

    //set the ontouch listener
    imageView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    ImageView view = (ImageView) v;
                    //overlay is black with transparency of 0x77 (119)
                    view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                    view.invalidate();
                    break;
                }
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL: {
                    ImageView view = (ImageView) v;
                    //clear the overlay
                    view.getDrawable().clearColorFilter();
                    view.invalidate();
                    break;
                }
            }

            return false;
        }
    });

I will probably be making this into a subclass of ImageView (or ImageButton as it is also a subclass of ImageView) for easier re-usability, but this should allow you to apply a "selected" look to an imageview.

How to check if a query string value is present via JavaScript?

You could also use a regular expression:

/[?&]q=/.test(location.search)

Prevent redirect after form is submitted

With out knowing exactly what your trying to accomplish here its hard to say but if your spending the time to solve this problem with javascript an AJAX request is going to be your best bet. However if you'd like to do it completely in PHP put this at the end of your script, and you should be set.

if(isset($_SERVER['HTTP_REFERER'])){
    header("Location: " . $_SERVER['HTTP_REFERER']);    
} else {
    echo "An Error";
}

This will still cause the page to change, twice, but the user will end on the page initiating the request. This is not even close to the right way to do this, and I highly recommend using an AJAX request, but it will get the job done.

pip install access denied on Windows

When all else fails, try quitting your IDE. I had many cases in which PyCharm was causing this. As soon as I quit PyCharm, I was able to finally install my packages from the command line. Alternatively, you can also install through PyCharm itself in Settings -> Project: xxx -> Project Interpreter -> +.

Check if list contains element that contains a string and get that element

Many good answers here, but I use a simple one using Exists, as below:

foreach (var setting in FullList)
{
    if(cleanList.Exists(x => x.ProcedureName == setting.ProcedureName)) 
       setting.IsActive = true; // do you business logic here 
    else
       setting.IsActive = false;
    updateList.Add(setting);
}

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

How did you declare the version?

<version>4.8.2</version>

Be aware of the meaning from this declaration explained here (see NOTES):

When declaring a "normal" version such as 3.8.2 for Junit, internally this is represented as "allow anything, but prefer 3.8.2." This means that when a conflict is detected, Maven is allowed to use the conflict algorithms to choose the best version. If you specify [3.8.2], it means that only 3.8.2 will be used and nothing else.

To force using the version 4.8.2 try

<version>[4.8.2]</version>

As you do not have any other dependencies in your project there shouldn't be any conflicts that cause your problem. The first declaration should work for you if you are able to get this version from a repository. Do you inherit dependencies from a parent pom?

Can you use @Autowired with static fields?

@Component("NewClass")
public class NewClass{
    private static SomeThing someThing;

    @Autowired
    public void setSomeThing(SomeThing someThing){
        NewClass.someThing = someThing;
    }
}

Build a basic Python iterator

If you looking for something short and simple, maybe it will be enough for you:

class A(object):
    def __init__(self, l):
        self.data = l

    def __iter__(self):
        return iter(self.data)

example of usage:

In [3]: a = A([2,3,4])

In [4]: [i for i in a]
Out[4]: [2, 3, 4]

redirect while passing arguments

You could pass the messages as explicit URL parameter (appropriately encoded), or store the messages into session (cookie) variable before redirecting and then get the variable before rendering the template. For example:

from flask import session, url_for

def do_baz():
    messages = json.dumps({"main":"Condition failed on page baz"})
    session['messages'] = messages
    return redirect(url_for('.do_foo', messages=messages))

@app.route('/foo')
def do_foo():
    messages = request.args['messages']  # counterpart for url_for()
    messages = session['messages']       # counterpart for session
    return render_template("foo.html", messages=json.loads(messages))

(encoding the session variable might not be necessary, flask may be handling it for you, but can't recall the details)

Or you could probably just use Flask Message Flashing if you just need to show simple messages.

Better way to convert an int to a boolean

I assume 0 means false (which is the case in a lot of programming languages). That means true is not 0 (some languages use -1 some others use 1; doesn't hurt to be compatible to either). So assuming by "better" you mean less typing, you can just write:

bool boolValue = intValue != 0;

Call to undefined function oci_connect()

Simple steps

You need to enable the below extension in your php.ini

;extension=php_oci8.dll
;extension=php_oci8_11.g.dll

by removing the ";" so that the results will below:

extension=php_oci8.dll
extension=php_oci8_11.g.dll

Download Oracle Instant Client:- Preferably 32 bit. 32 bit will also work on 64 bit. You can just google: download oracle instant client windows 32 bit. Use version 11 of the client because extension=php_oci8_11.g.dll won't work with 12. Unzip the package into a location such as C:\Oracle\instantclient_11_2.

Finally modify the System's PATH Environment Variable with end location, under system variables not user variables

Then you need to restart the System for PATH changes to fully propagate.

If you just restart XAMPP/WAMP without restarting the machine the Client's DLL files (i.e. OCL.dll) will not be loaded (nor found) by PHP's php_oci8_11g.dll extension.

Regular expression to match non-ASCII characters?

You do the same way as any other character matching, but you use \uXXXX where XXXX is the unicode number of the character.

Look at: http://unicode.org/charts/charindex.html

http://unicode.org/charts/

http://www.decodeunicode.org/

How to search text using php if ($text contains "World")

If you are looking an algorithm to rank search results based on relevance of multiple words here comes a quick and easy way of generating search results with PHP only.

Implementation of the vector space model in PHP

function get_corpus_index($corpus = array(), $separator=' ') {

    $dictionary = array();
    $doc_count = array();

    foreach($corpus as $doc_id => $doc) {
        $terms = explode($separator, $doc);
        $doc_count[$doc_id] = count($terms);

        // tf–idf, short for term frequency–inverse document frequency, 
        // according to wikipedia is a numerical statistic that is intended to reflect 
        // how important a word is to a document in a corpus

        foreach($terms as $term) {
            if(!isset($dictionary[$term])) {
                $dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
            }
            if(!isset($dictionary[$term]['postings'][$doc_id])) {
                $dictionary[$term]['document_frequency']++;
                $dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
            }

            $dictionary[$term]['postings'][$doc_id]['term_frequency']++;
        }

        //from http://phpir.com/simple-search-the-vector-space-model/

    }

    return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}

function get_similar_documents($query='', $corpus=array(), $separator=' '){

    $similar_documents=array();

    if($query!=''&&!empty($corpus)){

        $words=explode($separator,$query);
        $corpus=get_corpus_index($corpus);
        $doc_count=count($corpus['doc_count']);

        foreach($words as $word) {
            $entry = $corpus['dictionary'][$word];
            foreach($entry['postings'] as $doc_id => $posting) {

                //get term frequency–inverse document frequency
                $score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);

                if(isset($similar_documents[$doc_id])){
                    $similar_documents[$doc_id]+=$score;
                }
                else{
                    $similar_documents[$doc_id]=$score;
                }

            }
        }

        // length normalise
        foreach($similar_documents as $doc_id => $score) {
            $similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
        }

        // sort fro  high to low
        arsort($similar_documents);
    }   
    return $similar_documents;
}

IN YOUR CASE

$query = 'world';

$corpus = array(
    1 => 'hello world',
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

RESULTS

Array
(
    [1] => 0.79248125036058
)

MATCHING MULTIPLE WORDS AGAINST MULTIPLE PHRASES

$query = 'hello world';

$corpus = array(
    1 => 'hello world how are you today?',
    2 => 'how do you do world',
    3 => 'hello, here you are! how are you? Are we done yet?'
);

$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
    print_r($match_results);
echo '</pre>';

RESULTS

Array
(
    [1] => 0.74864218272161
    [2] => 0.43398500028846
)

from How do I check if a string contains a specific word in PHP?

how to delete all commit history in github?

If you are sure you want to remove all commit history, simply delete the .git directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:

git init
git remote add origin [email protected]:user/repo

now commit your current version of code

git add *
git commit -am 'message'

and finally force the update to GitHub:

git push -f origin master

However, I suggest backing up the history (the .git folder in the repository) before taking these steps!

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

It might be too late to answer this in 2019. but I tried all the answers and none worked for me. So I solved it simply this way:

@Html.EditorFor(m => m.SellDateForInstallment, "{0:dd/MM/yyyy}", 
               new {htmlAttributes = new { @class = "form-control", @type = "date" } })

EditorFor is what worked for me.

Note that SellDateForInstallment is a Nullable datetime object.

public DateTime? SellDateForInstallment { get; set; } // Model property

How can you detect the version of a browser?

You can see what the browser says, and use that information for logging or testing multiple browsers.

_x000D_
_x000D_
navigator.sayswho= (function(){_x000D_
    var ua= navigator.userAgent, tem, _x000D_
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];_x000D_
    if(/trident/i.test(M[1])){_x000D_
        tem=  /\brv[ :]+(\d+)/g.exec(ua) || [];_x000D_
        return 'IE '+(tem[1] || '');_x000D_
    }_x000D_
    if(M[1]=== 'Chrome'){_x000D_
        tem= ua.match(/\b(OPR|Edge)\/(\d+)/);_x000D_
        if(tem!= null) return tem.slice(1).join(' ').replace('OPR', 'Opera');_x000D_
    }_x000D_
    M= M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];_x000D_
    if((tem= ua.match(/version\/(\d+)/i))!= null) M.splice(1, 1, tem[1]);_x000D_
    return M.join(' ');_x000D_
})();_x000D_
_x000D_
console.log(navigator.sayswho); // outputs: `Chrome 62`
_x000D_
_x000D_
_x000D_

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

There are at least these two issues I have observed for this problem: 1) It could be either because your sender username or password might not be correct 2) Or it could be as answered by Avinash above, the security condition on the account. Once you try SendMail using SMTP, you normally get a notification in to your account that it may be an unauthorized attempt to access your account, if not user can follow the link to turn the settings to lessSecureApp. Once this is done and smtp SendMail is tried again, it works.

Why SpringMVC Request method 'GET' not supported?

Change

@RequestMapping(value = "/test", method = RequestMethod.POST)

To

@RequestMapping(value = "/test", method = RequestMethod.GET)

Convert time in HH:MM:SS format to seconds only?

    $time = 00:06:00;
    $timeInSeconds = strtotime($time) - strtotime('TODAY');

How to list active / open connections in Oracle?

select
  username,
  osuser,
  terminal,
  utl_inaddr.get_host_address(terminal) IP_ADDRESS
from
  v$session
where
  username is not null
order by
  username,
  osuser;

How to normalize a 2-dimensional numpy array in python less verbose?

it appears that this also works

def normalizeRows(M):
    row_sums = M.sum(axis=1)
    return M / row_sums

How to read xml file contents in jQuery and display in html elements?

First of all create on file and then convert your xml data in array and retrieve that data in json format for ajax success response.

Try as below:

$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "sample.php",            
        success: function (response) {
            var obj = $.parseJSON(response);
            for(var i=0;i<obj.length;i++){
                // here you can add html through loop
            }                
        }
    });
});  

sample.php

$xml = "YOUR XML FILE PATH";
$json = json_encode((array)simplexml_load_string($xml)),1);
echo $json;

How can I make the computer beep in C#?

The solution would be,

Console.Beep

Difference between jar and war in Java

From Java Tips: Difference between ear jar and war files:

These files are simply zipped files using the java jar tool. These files are created for different purposes. Here is the description of these files:

  • .jar files: The .jar files contain libraries, resources and accessories files like property files.

  • .war files: The war file contains the web application that can be deployed on any servlet/jsp container. The .war file contains jsp, html, javascript and other files necessary for the development of web applications.


Official Sun/Oracle descriptions:


Wikipedia articles:

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

How can I check if the array of objects have duplicate property values?

ECMA Script 6 Version

If you are in an environment which supports ECMA Script 6's Set, then you can use Array.prototype.some and a Set object, like this

let seen = new Set();
var hasDuplicates = values.some(function(currentObject) {
    return seen.size === seen.add(currentObject.name).size;
});

Here, we insert each and every object's name into the Set and we check if the size before and after adding are the same. This works because Set.size returns a number based on unique data (set only adds entries if the data is unique). If/when you have duplicate names, the size won't increase (because the data won't be unique) which means that we would have already seen the current name and it will return true.


ECMA Script 5 Version

If you don't have Set support, then you can use a normal JavaScript object itself, like this

var seen = {};
var hasDuplicates = values.some(function(currentObject) {

    if (seen.hasOwnProperty(currentObject.name)) {
        // Current name is already seen
        return true;
    }

    // Current name is being seen for the first time
    return (seen[currentObject.name] = false);
});

The same can be written succinctly, like this

var seen = {};
var hasDuplicates = values.some(function (currentObject) {
    return seen.hasOwnProperty(currentObject.name)
        || (seen[currentObject.name] = false);
});

Note: In both the cases, we use Array.prototype.some because it will short-circuit. The moment it gets a truthy value from the function, it will return true immediately, it will not process rest of the elements.

How do I get the key at a specific index from a Dictionary in Swift?

In Swift 3 try to use this code to get Key-Value Pair (tuple) at given index:

extension Dictionary {
    subscript(i:Int) -> (key:Key,value:Value) {
        get {
            return self[index(startIndex, offsetBy: i)];
        }
    }
}

Setting a property with an EventTrigger

Just create your own action.

namespace WpfUtil
{
    using System.Reflection;
    using System.Windows;
    using System.Windows.Interactivity;


    /// <summary>
    /// Sets the designated property to the supplied value. TargetObject
    /// optionally designates the object on which to set the property. If
    /// TargetObject is not supplied then the property is set on the object
    /// to which the trigger is attached.
    /// </summary>
    public class SetPropertyAction : TriggerAction<FrameworkElement>
    {
        // PropertyName DependencyProperty.

        /// <summary>
        /// The property to be executed in response to the trigger.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty
            = DependencyProperty.Register("PropertyName", typeof(string),
            typeof(SetPropertyAction));


        // PropertyValue DependencyProperty.

        /// <summary>
        /// The value to set the property to.
        /// </summary>
        public object PropertyValue
        {
            get { return GetValue(PropertyValueProperty); }
            set { SetValue(PropertyValueProperty, value); }
        }

        public static readonly DependencyProperty PropertyValueProperty
            = DependencyProperty.Register("PropertyValue", typeof(object),
            typeof(SetPropertyAction));


        // TargetObject DependencyProperty.

        /// <summary>
        /// Specifies the object upon which to set the property.
        /// </summary>
        public object TargetObject
        {
            get { return GetValue(TargetObjectProperty); }
            set { SetValue(TargetObjectProperty, value); }
        }

        public static readonly DependencyProperty TargetObjectProperty
            = DependencyProperty.Register("TargetObject", typeof(object),
            typeof(SetPropertyAction));


        // Private Implementation.

        protected override void Invoke(object parameter)
        {
            object target = TargetObject ?? AssociatedObject;
            PropertyInfo propertyInfo = target.GetType().GetProperty(
                PropertyName,
                BindingFlags.Instance|BindingFlags.Public
                |BindingFlags.NonPublic|BindingFlags.InvokeMethod);

            propertyInfo.SetValue(target, PropertyValue);
        }
    }
}

In this case I'm binding to a property called DialogResult on my viewmodel.

<Grid>

    <Button>
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <wpf:SetPropertyAction PropertyName="DialogResult" TargetObject="{Binding}"
                                       PropertyValue="{x:Static mvvm:DialogResult.Cancel}"/>
            </i:EventTrigger>
        </i:Interaction.Triggers>
        Cancel
    </Button>

</Grid>

How to compare 2 dataTables

Inspired by samneric's answer using DataRowComparer.Default but needing something that would only compare a subset of columns within a DataTable, I made a DataTableComparer object where you can specify which columns to use in the comparison. Especially great if they have different columns/schemas.

DataRowComparer.Default works because it implements IEqualityComparer. Then I created an object where you can define which columns of the DataRow will be compared.

public class DataTableComparer : IEqualityComparer<DataRow>
{
    private IEnumerable<String> g_TestColumns;
    public void SetCompareColumns(IEnumerable<String> p_Columns)
    {
        g_TestColumns = p_Columns; 
    }

    public bool Equals(DataRow x, DataRow y)
    {

        foreach (String sCol in g_TestColumns)
            if (!x[sCol].Equals(y[sCol])) return false;

        return true;
    }

    public int GetHashCode(DataRow obj)
    {
        StringBuilder hashBuff = new StringBuilder();

        foreach (String sCol in g_TestColumns)
            hashBuff.AppendLine(obj[sCol].ToString());               

        return hashBuff.ToString().GetHashCode();

    }
}

You can use this by:

DataTableComparer comp = new DataTableComparer();
comp.SetCompareColumns(new String[] { "Name", "DoB" });

DataTable celebrities = SomeDataTableSource();
DataTable politicians = SomeDataTableSource2();

List<DataRow> celebrityPoliticians = celebrities.AsEnumerable().Intersect(politicians.AsEnumerable(), comp).ToList();

How to get all Errors from ASP.Net MVC modelState?

In your implementation you are missing static Class, this should be.

if (!ModelState.IsValid)
{
    var errors =  ModelStateErrorHandler.GetModelErrors(this.ModelState);
    return Json(new { errors });
}

rather

if (!ModelState.IsValid)
{
    var errors = ModelState.GetModelErrors();
    return Json(new { errors });
}

What is the use of GO in SQL Server Management Studio & Transact SQL?

Since Management Studio 2005 it seems that you can use GO with an int parameter, like:

INSERT INTO mytable DEFAULT VALUES
GO 10

The above will insert 10 rows into mytable. Generally speaking, GO will execute the related sql commands n times.

how to check if object already exists in a list

Edit: I had first said:


What's inelegant about the dictionary solution. It seems perfectly elegant to me, esp since you only need to set the comparator in creation of the dictionary.


Of course though, it is inelegant to use something as a key when it's also the value.

Therefore I would use a HashSet. If later operations required indexing, I'd create a list from it when the Adding was done, otherwise, just use the hashset.

Regular Expression to select everything before and up to a particular text

((\n.*){0,3})(.*)\W*\.txt

This will select all the content before the particular word ".txt" including any context in different lines up to 3 lines

If isset $_POST

Maybe you can try this one:

if (isset($_POST['mail']) && ($_POST['mail'] !=0)) { echo "Yes, mail is set"; } else { echo "No, mail is not set"; }

How to get row number in dataframe in Pandas?

To get all indices that matches 'Smith'

>>> df[df['LastName'] == 'Smith'].index
Int64Index([1], dtype='int64')

or as a numpy array

>>> df[df['LastName'] == 'Smith'].index.to_numpy()  # .values on older versions
array([1])

or if there is only one and you want the integer, you can subset

>>> df[df['LastName'] == 'Smith'].index[0]
1

You could use the same boolean expressions with .loc, but it is not needed unless you also want to select a certain column, which is redundant when you only want the row number/index.

MySQL select where column is not empty

Compare value of phone2 with empty string:

select phone, phone2 
from jewishyellow.users 
where phone like '813%' and phone2<>''

Note that NULL value is interpreted as false.

Pass variables between two PHP pages without using a form or the URL of page

Use Sessions.

Page1:

session_start();
$_SESSION['message'] = "Some message"

Page2:

session_start();
var_dump($_SESSION['message']);

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

Retrieve the commit log for a specific line in a file?

Here is a solution that defines a git alias, so you will be able use it like that :

git rblame -M -n -L '/REGEX/,+1' FILE

Output example :

00000000 18 (Not Committed Yet 2013-08-19 13:04:52 +0000 728) fooREGEXbar
15227b97 18 (User1 2013-07-11 18:51:26 +0000 728) fooREGEX
1748695d 23 (User2 2013-03-19 21:09:09 +0000 741) REGEXbar

You can define the alias in your .gitconfig or simply run the following command

git config alias.rblame !sh -c 'while line=$(git blame "$@" $commit 2>/dev/null); do commit=${line:0:8}^; [ 00000000^ == $commit ] && commit=$(git rev-parse HEAD); echo $line; done' dumb_param

This is an ugly one-liner, so here is a de-obfuscated equivalent bash function :

git-rblame () {
    local commit line
    while line=$(git blame "$@" $commit 2>/dev/null); do
        commit="${line:0:8}^"
        if [ "00000000^" == "$commit" ]; then
            commit=$(git rev-parse HEAD)
        fi
        echo $line
    done
}

The pickaxe solution ( git log --pickaxe-regex -S'REGEX' ) will only give you line additions/deletions, not the other alterations of the line containing the regular expression.

A limitation of this solution is that git blame only returns the 1st REGEX match, so if multiple matches exist the recursion may "jump" to follow another line. Be sure to check the full history output to spot those "jumps" and then fix your REGEX to ignore the parasite lines.

Finally, here is an alternate version that run git show on each commit to get the full diff :

git config alias.rblameshow !sh -c 'while line=$(git blame "$@" $commit 2>/dev/null); do commit=${line:0:8}^; [ 00000000^ == $commit ] && commit=$(git rev-parse HEAD); git show $commit; done' dumb_param

How to parse/format dates with LocalDateTime? (Java 8)

Both answers above explain very well the question regarding string patterns. However, just in case you are working with ISO 8601 there is no need to apply DateTimeFormatter since LocalDateTime is already prepared for it:

Convert LocalDateTime to Time Zone ISO8601 String

LocalDateTime ldt = LocalDateTime.now(); 
ZonedDateTime zdt = ldt.atZone(ZoneOffset.UTC); //you might use a different zone
String iso8601 = zdt.toString();

Convert from ISO8601 String back to a LocalDateTime

String iso8601 = "2016-02-14T18:32:04.150Z";
ZonedDateTime zdt = ZonedDateTime.parse(iso8601);
LocalDateTime ldt = zdt.toLocalDateTime();

How to add a RequiredFieldValidator to DropDownList control?

If you are using a data source, here's another way to do it without code behind.

Note the following key points:

  • The ListItem of Value="0" is on the source page, not added in code
  • The ListItem in the source will be overwritten if you don't include AppendDataBoundItems="true" in the DropDownList
  • InitialValue="0" tells the validator that this is the value that should fire that validator (as pointed out in other answers)

Example:

<asp:DropDownList ID="ddlType" runat="server" DataSourceID="sdsType"
                  DataValueField="ID" DataTextField="Name" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="--Please Select--" Selected="True"></asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="rfvType" runat="server" ControlToValidate="ddlType" 
                            InitialValue="0" ErrorMessage="Type required"></asp:RequiredFieldValidator>
<asp:SqlDataSource ID="sdsType" runat="server" 
                   ConnectionString='<%$ ConnectionStrings:TESTConnectionString %>'
                   SelectCommand="SELECT ID, Name FROM Type"></asp:SqlDataSource>

if checkbox is checked, do this

Try this.

$('#checkbox').click(function(){
    if (this.checked) {
        $('p').css('color', '#0099ff')
    }
}) 

Sometimes we overkill jquery. Many things can be achieved using jquery with plain javascript.

Where is GACUTIL for .net Framework 4.0 in windows 7?

There actually is now a GAC Utility for .NET 4.0. It is found in the Microsoft Windows 7 and .NET 4.0 SDK (the SDK supports multiple OSs -- not just Windows 7 -- so if you are using a later OS from Microsoft the odds are good that it's supported).

This is the SDK. You can download the ISO or do a Web install. Kind-of overkill to download the entire thing if all you want is the GAC Util; however, it does work.

Disable elastic scrolling in Safari

overflow:hidden;-webkit-overflow-scrolling:touch won't work well on iOS safari 8.1, as the fixed header will be out of visible area.

gif

As @Yisela says, the css should be placed on .container(the <div> below <body>). which seems no problem(at leas on safari iOS 8.1)

gif

I've place the demo on my blog: http://tech.colla.me/en/show/disable_elastic_scroll_on_iOS_safari

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Rationale for the / POSIX PATH rule

The rule was mentioned at: Why do you need ./ (dot-slash) before executable or script name to run it in bash? but I would like to explain why I think that is a good design in more detail.

First, an explicit full version of the rule is:

  • if the path contains / (e.g. ./someprog, /bin/someprog, ./bin/someprog): CWD is used and PATH isn't
  • if the path does not contain / (e.g. someprog): PATH is used and CWD isn't

Now, suppose that running:

someprog

would search:

  • relative to CWD first
  • relative to PATH after

Then, if you wanted to run /bin/someprog from your distro, and you did:

someprog

it would sometimes work, but others it would fail, because you might be in a directory that contains another unrelated someprog program.

Therefore, you would soon learn that this is not reliable, and you would end up always using absolute paths when you want to use PATH, therefore defeating the purpose of PATH.

This is also why having relative paths in your PATH is a really bad idea. I'm looking at you, node_modules/bin.

Conversely, suppose that running:

./someprog

Would search:

  • relative to PATH first
  • relative to CWD after

Then, if you just downloaded a script someprog from a git repository and wanted to run it from CWD, you would never be sure that this is the actual program that would run, because maybe your distro has a:

/bin/someprog

which is in you PATH from some package you installed after drinking too much after Christmas last year.

Therefore, once again, you would be forced to always run local scripts relative to CWD with full paths to know what you are running:

"$(pwd)/someprog"

which would be extremely annoying as well.

Another rule that you might be tempted to come up with would be:

relative paths use only PATH, absolute paths only CWD

but once again this forces users to always use absolute paths for non-PATH scripts with "$(pwd)/someprog".

The / path search rule offers a simple to remember solution to the about problem:

  • slash: don't use PATH
  • no slash: only use PATH

which makes it super easy to always know what you are running, by relying on the fact that files in the current directory can be expressed either as ./somefile or somefile, and so it gives special meaning to one of them.

Sometimes, is slightly annoying that you cannot search for some/prog relative to PATH, but I don't see a saner solution to this.

Detect when input has a 'readonly' attribute

try this:

if($('input').attr('readonly') == undefined){
    alert("foo");
}

if it is not there it will be undefined in js