Programs & Examples On #Windows mobile gps

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

You can use below code for your solution:-

public void Linq94() 
{ 
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
    int[] numbersB = { 1, 3, 5, 7, 8 }; 

    var allNumbers = numbersA.Concat(numbersB); 

    Console.WriteLine("All numbers from both arrays:"); 
    foreach (var n in allNumbers) 
    { 
        Console.WriteLine(n); 
    } 
}

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    public static void main(String[] args) throws IOException {

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

When should I use Async Controllers in ASP.NET MVC?

async actions help best when the actions does some I\O operations to DB or some network bound calls where the thread that processes the request will be stalled before it gets answer from the DB or network bound call which you just invoked. It's best you use await with them and it will really improve the responsiveness of your application (because less ASP input\output threads will be stalled while waiting for the DB or any other operation like that). In all my applications whenever many calls to DB very necessary I've always wrapped them in awaiatable method and called that with await keyword.

how to get all markers on google-maps-v3

Google Maps API v3:

I initialized Google Map and added markers to it. Later, I wanted to retrieve all markers and did it simply by accessing the map property "markers".

var map = new GMaps({
    div: '#map',
    lat: 40.730610,
    lng: -73.935242,
});

var myMarkers = map.markers;

You can loop over it and access all Marker methods listed at Google Maps Reference.

NodeJS: How to get the server's port?

I use this way Express 4:

app.listen(1337, function(){
  console.log('Express listening on port', this.address().port);
});

By using this I don't need to use a separate variable for the listener/server.

Storing data into list with class

If you want to instantiate and add in the same line, you'd have to do something like this:

lstemail.Add(new EmailData { FirstName = "JOhn", LastName = "Smith", Location = "Los Angeles" });

or just instantiate the object prior, and add it directly in:

EmailData data = new EmailData();
data.FirstName = "JOhn";
data.LastName = "Smith";
data.Location = "Los Angeles"

lstemail.Add(data);

Javascript wait() function

You shouldn't edit it, you should completely scrap it.

Any attempt to make execution stop for a certain amount of time will lock up the browser and switch it to a Not Responding state. The only thing you can do is use setTimeout correctly.

What's the best way to test SQL Server connection programmatically?

For what Joel Coehorn suggested, have you already tried the utility named tcping. I know this is something you are not doing programmatically. It is a standalone executable which allows you to ping every specified time interval. It is not in C# though. Also..I am not sure If this would work If the target machine has firewall..hmmm..

[I am kinda new to this site and mistakenly added this as a comment, now added this as an answer. Let me know If this can be done here as I have duplicate comments (as comment and as an answer) here. I can not delete comments here.]

How to refer to Excel objects in Access VBA?

First you need to set a reference (Menu: Tools->References) to the Microsoft Excel Object Library then you can access all Excel Objects.

After you added the Reference you have full access to all Excel Objects. You need to add Excel in front of everything for example:

Dim xlApp as Excel.Application

Let's say you added an Excel Workbook Object in your Form and named it xLObject.

Here is how you Access a Sheet of this Object and change a Range

Dim sheet As Excel.Worksheet
Set sheet = xlObject.Object.Sheets(1)
sheet.Range("A1") = "Hello World"

(I copied the above from my answer to this question)

Another way to use Excel in Access is to start Excel through a Access Module (the way shahkalpesh described it in his answer)

How to make IPython notebook matplotlib plot inline

I had the same problem when I was running the plotting commands in separate cells in Jupyter:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         <Figure size 432x288 with 0 Axes>                      #this might be the problem
In [4]:  ax = fig.add_subplot(1, 1, 1)
In [5]:  ax.scatter(x, y)
Out[5]:  <matplotlib.collections.PathCollection at 0x12341234>  # CAN'T SEE ANY PLOT :(
In [6]:  plt.show()                                             # STILL CAN'T SEE IT :(

The problem was solved by merging the plotting commands into a single cell:

In [1]:  %matplotlib inline
         import matplotlib
         import matplotlib.pyplot as plt
         import numpy as np
In [2]:  x = np.array([1, 3, 4])
         y = np.array([1, 5, 3])
In [3]:  fig = plt.figure()
         ax = fig.add_subplot(1, 1, 1)
         ax.scatter(x, y)
Out[3]:  <matplotlib.collections.PathCollection at 0x12341234>
         # AND HERE APPEARS THE PLOT AS DESIRED :)

Accessing clicked element in angularjs

While AngularJS allows you to get a hand on a click event (and thus a target of it) with the following syntax (note the $event argument to the setMaster function; documentation here: http://docs.angularjs.org/api/ng.directive:ngClick):

function AdminController($scope) {    
  $scope.setMaster = function(obj, $event){
    console.log($event.target);
  }
}

this is not very angular-way of solving this problem. With AngularJS the focus is on the model manipulation. One would mutate a model and let AngularJS figure out rendering.

The AngularJS-way of solving this problem (without using jQuery and without the need to pass the $event argument) would be:

<div ng-controller="AdminController">
    <ul class="list-holder">
        <li ng-repeat="section in sections" ng-class="{active : isSelected(section)}">
            <a ng-click="setMaster(section)">{{section.name}}</a>
        </li>
    </ul>
    <hr>
    {{selected | json}}
</div>

where methods in the controller would look like this:

$scope.setMaster = function(section) {
    $scope.selected = section;
}

$scope.isSelected = function(section) {
    return $scope.selected === section;
}

Here is the complete jsFiddle: http://jsfiddle.net/pkozlowski_opensource/WXJ3p/15/

How do I download a file with Angular2 or greater

The problem is that the observable runs in another context, so when you try to create the URL var, you have an empty object and not the blob you want.

One of the many ways that exist to solve this is as follows:

this._reportService.getReport().subscribe(data => this.downloadFile(data)),//console.log(data),
                 error => console.log('Error downloading the file.'),
                 () => console.info('OK');

When the request is ready it will call the function "downloadFile" that is defined as follows:

downloadFile(data: Response) {
  const blob = new Blob([data], { type: 'text/csv' });
  const url= window.URL.createObjectURL(blob);
  window.open(url);
}

the blob has been created perfectly and so the URL var, if doesn't open the new window please check that you have already imported 'rxjs/Rx' ;

  import 'rxjs/Rx' ;

I hope this can help you.

How to view DB2 Table structure

drop view lawmod9t.vdesc

create view lawmod9t.vDesc as select 
       upper(t.table_cat) as Catalog, 
       upper(t.table_schem) as Schema, 
       upper(t.table_name) as table, 
       t.table_text as tableDesc, 
       c.system_column_name as colname_short, 
       c.column_name as colname_long, 
       c.column_text as coldesc, 
       c.Type_Name as type, 
       c.column_Size as size
from sysibm.SQLColumns c
inner join sysibm.sqltables t
on c.table_schem = t.table_schem
and c.table_name = t.table_name

select * from vdesc where table = 'YPPPOPL'

Javascript/jQuery detect if input is focused

Did you try:

$(this).is(':focus');

Take a look at Using jQuery to test if an input has focus it features some more examples

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

Set the layout weight of a TextView programmatically

TextView text = new TextView(v.getContext());
text.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                                                LayoutParams.WRAP_CONTENT, 1f));

(OR)

TextView tv = new TextView(v.getContext());
LayoutParams params = new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
tv.setLayoutParams(params);

1f is refered as weight=1; according to your need you can give 2f or 3f, views will move accoding to the space. For making specified distance between views in Linear layout use weightsum for "LinearLayout".

LinearLayout ll_Outer= (LinearLayout ) view.findViewById(R.id.linearview);
LinearLayout llInner = new LinearLayout(this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FillParent, LinearLayout.LayoutParams.WrapContent);
            llInner.Orientation = Orientation.Horizontal;
            llInner.WeightSum = 2;
            ll_Outer.AddView(llInner);

Image style height and width not taken in outlook mails

This worked for me:

src="{0}"  width=30 height=30 style="border:0;"

Nothing else has worked so far.

Deadly CORS when http://localhost is the origin

I decided not to touch headers and make a redirect on the server side instead and it woks like a charm.

The example below is for the current version of Angular (currently 9) and probably any other framework using webpacks DevServer. But I think the same principle will work on other backends.

So I use the following configuration in the file proxy.conf.json:

{
  "/api": {
    "target": "http://localhost:3000",
    "pathRewrite": {"^/api" : ""},
   "secure": false
 }
}

In case of Angular I serve with that configuration:

$ ng serve -o --proxy-config=proxy.conf.json

I prefer to use the proxy in the serve command, but you may also put this configuration to angular.json like this:

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },

See also:

https://www.techiediaries.com/fix-cors-with-angular-cli-proxy-configuration/

https://webpack.js.org/configuration/dev-server/#devserverproxy

Convert String to Float in Swift

Because in some parts of the world, for example, a comma is used instead of a decimal. It is best to create a NSNumberFormatter to convert a string to float.

let numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
let number = numberFormatter.numberFromString(self.stringByTrimmingCharactersInSet(Wage.text))

Postgresql SELECT if string contains

A proper way to search for a substring is to use position function instead of like expression, which requires escaping %, _ and an escape character (\ by default):

SELECT id FROM TAG_TABLE WHERE position(tag_name in 'aaaaaaaaaaa')>0;

How to apply a function to two columns of Pandas dataframe

A interesting question! my answer as below:

import pandas as pd

def sublst(row):
    return lst[row['J1']:row['J2']]

df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
print df
lst = ['a','b','c','d','e','f']

df['J3'] = df.apply(sublst,axis=1)
print df

Output:

  ID  J1  J2
0  1   0   1
1  2   2   4
2  3   3   5
  ID  J1  J2      J3
0  1   0   1     [a]
1  2   2   4  [c, d]
2  3   3   5  [d, e]

I changed the column name to ID,J1,J2,J3 to ensure ID < J1 < J2 < J3, so the column display in right sequence.

One more brief version:

import pandas as pd

df = pd.DataFrame({'ID':['1','2','3'], 'J1': [0,2,3], 'J2':[1,4,5]})
print df
lst = ['a','b','c','d','e','f']

df['J3'] = df.apply(lambda row:lst[row['J1']:row['J2']],axis=1)
print df

How can I generate UUID in C#

Be careful: while the string representations for .NET Guid and (RFC4122) UUID are identical, the storage format is not. .NET trades in little-endian bytes for the first three Guid parts.

If you are transmitting the bytes (for example, as base64), you can't just use Guid.ToByteArray() and encode it. You'll need to Array.Reverse the first three parts (Data1-3).

I do it this way:

var rfc4122bytes = Convert.FromBase64String("aguidthatIgotonthewire==");
Array.Reverse(rfc4122bytes,0,4);
Array.Reverse(rfc4122bytes,4,2);
Array.Reverse(rfc4122bytes,6,2);
var guid = new Guid(rfc4122bytes);

See this answer for the specific .NET implementation details.

Edit: Thanks to Jeff Walker, Code Ranger, for pointing out that the internals are not relevant to the format of the byte array that goes in and out of the byte-array constructor and ToByteArray().

ToggleButton in C# WinForms

thers is a simple way to create toggle button. I test it in vs2010. It's perfect.

ToolStripButton has a "Checked" property and a "CheckOnClik" property. You can use it to act as a toggle button

tbtnCross.CheckOnClick = true;

OR

    tbtnCross.CheckOnClick = false;
    tbtnCross.Click += new EventHandler(tbtnCross_Click);
    .....

    void tbtnCross_Click(object sender, EventArgs e)
    {
        ToolStripButton target = sender as ToolStripButton;
        target.Checked = !target.Checked;
    }

also, You can create toggle button list like this:

        private void Form1_Load(object sender, EventArgs e)
    {
        arrToolView[0] = tbtnCross;
        arrToolView[1] = tbtnLongtitude;
        arrToolView[2] = tbtnTerrain;
        arrToolView[3] = tbtnResult;
        for (int i = 0; i<arrToolView.Length; i++)
        {
            arrToolView[i].CheckOnClick = false;
            arrToolView[i].Click += new EventHandler(tbtnView_Click);
        }
        InitTree();
    }

    void tbtnView_Click(object sender, EventArgs e)
    {
        ToolStripButton target = sender as ToolStripButton;
        if (target.Checked) return;
        foreach (ToolStripButton btn in arrToolView)
        {
                btn.Checked = false;
                //btn.CheckState = CheckState.Unchecked;
        }
        target.Checked = true;
        target.CheckState = CheckState.Checked;

    }

Execute PHP function with onclick

Solution without page reload

<?php
  function removeday() { echo 'Day removed'; }

  if (isset($_GET['remove'])) { return removeday(); }
?>


<!DOCTYPE html><html><title>Days</title><body>

  <a href="" onclick="removeday(event)" class="deletebtn">Delete</a>

  <script>
  async function removeday(e) {
    e.preventDefault(); 
    document.body.innerHTML+= '<br>'+ await(await fetch('?remove=1')).text();
  }
  </script>

</body></html>

Creating table variable in SQL server 2008 R2

@tableName Table variables are alive for duration of the script running only i.e. they are only session level objects.

To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.

There is another type of table object which can be created for temporary use. They are #tableName objects declared like similar create statement for physical tables:

Create table #test (Id int, Name varchar(50))

This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.

IF OBJECT_ID('tempdb..#test') IS NOT NULL
  DROP TABLE #test 

Hope this makes sense !

How to move an element into another element?

I just used:

$('#source').prependTo('#destination');

Which I grabbed from here.

How to check if a process is in hang state (Linux)

Is there any command in Linux through which i can know if the process is in hang state.

There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):

  • run ps to find list of PIDs of the watched processes (along with exec time, etc)
  • loop over the PIDs
  • start gdb attaching to the process using its PID, dumping stack trace from it using thread apply all where, detaching from the process
  • a process was declared hung if:
    • its stack trace didn't change and time didn't change after 3 checks
    • its stack trace didn't change and time was indicating 100% CPU load after 3 checks
  • hung process was killed to give a chance for a monitoring application to restart the hung instance.

But that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.

Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.

The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

Entity state transitions

JPA translates entity state transitions to SQL statements, like INSERT, UPDATE or DELETE.

JPA entity state transitions

When you persist an entity, you are scheduling the INSERT statement to be executed when the EntityManager is flushed, either automatically or manually.

when you remove an entity, you are scheduling the DELETE statement, which will be executed when the Persistence Context is flushed.

Cascading entity state transitions

For convenience, JPA allows you to propagate entity state transitions from parent entities to child one.

So, if you have a parent Post entity that has a @OneToMany association with the PostComment child entity:

Post and PostComment entities

The comments collection in the Post entity is mapped as follows:

@OneToMany(
    mappedBy = "post", 
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<Comment> comments = new ArrayList<>();

CascadeType.ALL

The cascade attribute tells the JPA provider to pass the entity state transition from the parent Post entity to all PostComment entities contained in the comments collection.

So, if you remove the Post entity:

Post post = entityManager.find(Post.class, 1L);
assertEquals(2, post.getComments().size());

entityManager.remove(post);

The JPA provider is going to remove the PostComment entity first, and when all child entities are deleted, it will delete the Post entity as well:

DELETE FROM post_comment WHERE id = 1
DELETE FROM post_comment WHERE id = 2

DELETE FROM post WHERE id = 1

Orphan removal

When you set the orphanRemoval attribute to true, the JPA provider is going to schedule a remove operation when the child entity is removed from the collection.

So, in our case,

Post post = entityManager.find(Post.class, 1L);
assertEquals(2, post.getComments().size());

PostComment postComment = post.getComments().get(0);
assertEquals(1L, postComment.getId());

post.getComments().remove(postComment);

The JPA provider is going to remove the associated post_comment record since the PostComment entity is no longer referenced in the comments collection:

DELETE FROM post_comment WHERE id = 1

ON DELETE CASCADE

The ON DELETE CASCADE is defined at the FK level:

ALTER TABLE post_comment 
ADD CONSTRAINT fk_post_comment_post_id 
FOREIGN KEY (post_id) REFERENCES post 
ON DELETE CASCADE;

Once you do that, if you delete a post row:

DELETE FROM post WHERE id = 1

All the associated post_comment entities are removed automatically by the database engine. However, this can be a very dangerous operation if you delete a root entity by mistake.

Conclusion

The advantage of the JPA cascade and orphanRemoval options is that you can also benefit from optimistic locking to prevent lost updates.

If you use the JPA cascading mechanism, you don't need to use DDL-level ON DELETE CASCADE, which can be a very dangerous operation if you remove a root entity that has many child entities on multiple levels.

Check if a user has scrolled to the bottom

Many other solutions doesn't work for me Because on scroll to bottom my div was triggering the alert 2 times and when moving up it was also trigerring upto a few pixels so The solution is:

        $('#your-div').on('resize scroll', function()
        {
            if ($(this).scrollTop() +
                $(this).innerHeight() >=
                $(this)[0].scrollHeight + 10) {

                alert('reached bottom!');
            }
        });

Updating user data - ASP.NET Identity

I also had problems using UpdateAsync when developing a version of SimpleSecurity that uses ASP.NET Identity. For example, I added a feature to do a password reset that needed to add a password reset token to the user information. At first I tried using UpdateAsync and it got the same results as you did. I ended up wrapping the user entity in a repository pattern and got it to work. You can look at the SimpleSecurity project for an example. After working with ASP.NET Identity more (documentation is still non-existent) I think that UpdateAsync just commits the update to the context, you still need to save the context for it to commit to the database.

Choosing line type and color in Gnuplot 4.0

I know the question is old but I found this very helpful http://www.gnuplot.info/demo_canvas/dashcolor.html . So you can choose linetype and linecolor separately but you have to precede everything by "set termoption dash" (worked for me in gnuplot 4.4).

What is EOF in the C programming language?

EOF means end of file. It's a sign that the end of a file is reached, and that there will be no data anymore.

Edit:

I stand corrected. In this case it's not an end of file. As mentioned, it is passed when CTRL+d (linux) or CTRL+z (windows) is passed.

How to upgrade glibc from version 2.13 to 2.15 on Debian?

I was able to install libc6 2.17 in Debian Wheezy by editing the recommendations in perror's answer:

IMPORTANT
You need to exit out of your display manager by pressing CTRL-ALT-F1. Then you can stop x (slim) with sudo /etc/init.d/slim stop

(replace slim with mdm or lightdm or whatever)

Add the following line to the file /etc/apt/sources.list:

deb http://ftp.debian.org/debian experimental main

Should be changed to:

deb http://ftp.debian.org/debian sid main

Then follow the rest of perror's post:

Update your package database:

apt-get update

Install the eglibc package:

apt-get -t sid install libc6-amd64 libc6-dev libc6-dbg

IMPORTANT
After done updating libc6, restart computer, and you should comment out or remove the sid source you just added (deb http://ftp.debian.org/debian sid main), or else you risk upgrading your whole distro to sid.

Hope this helps. It took me a while to figure out.

What does "var" mean in C#?

It means the data type is derived (implied) from the context.

From http://msdn.microsoft.com/en-us/library/bb383973.aspx

Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

var is useful for eliminating keyboard typing and visual noise, e.g.,

MyReallyReallyLongClassName x = new MyReallyReallyLongClassName();

becomes

var x = new MyReallyReallyLongClassName();

but can be overused to the point where readability is sacrificed.

java build path problems

Go for the second option, Edit the project to agree with the latest JDK

  • Right click "JRE System Library [J2SE 1.5] in your project"
  • Choose "Properties"
  • Select "Workspace default JRE (jdk1.6)

enter image description here

PHP Try and Catch for SQL Insert

This can do the trick,

function createLog($data){ 
    $file = "Your path/incompletejobs.txt";
    $fh = fopen($file, 'a') or die("can't open file");
    fwrite($fh,$data);
    fclose($fh);
}
$qry="INSERT INTO redirects SET ua_string = '$ua_string'"   
$result=mysql_query($qry);
if(!$result){
    createLog(mysql_error());
}

How do I make a list of data frames?

This may be a little late but going back to your example I thought I would extend the answer just a tad.

 D1 <- data.frame(Y1=c(1,2,3), Y2=c(4,5,6))
 D2 <- data.frame(Y1=c(3,2,1), Y2=c(6,5,4))
 D3 <- data.frame(Y1=c(6,5,4), Y2=c(3,2,1))
 D4 <- data.frame(Y1=c(9,9,9), Y2=c(8,8,8))

Then you make your list easily:

mylist <- list(D1,D2,D3,D4)

Now you have a list but instead of accessing the list the old way such as

mylist[[1]] # to access 'd1'

you can use this function to obtain & assign the dataframe of your choice.

GETDF_FROMLIST <- function(DF_LIST, ITEM_LOC){
   DF_SELECTED <- DF_LIST[[ITEM_LOC]]
   return(DF_SELECTED)
}

Now get the one you want.

D1 <- GETDF_FROMLIST(mylist, 1)
D2 <- GETDF_FROMLIST(mylist, 2)
D3 <- GETDF_FROMLIST(mylist, 3)
D4 <- GETDF_FROMLIST(mylist, 4)

Hope that extra bit helps.

Cheers!

Are there any style options for the HTML5 Date picker?

I used a combination of the above solutions and some trial and error to come to this solution. Took me an annoying amount of time so I hope this can help someone else in the future. I also noticed that the date picker input is not at all supported by Safari...

I am using styled-components to render a transparent date picker input as shown in the image below:

image of date picker input

const StyledInput = styled.input`
  appearance: none;
  box-sizing: border-box;
  border: 1px solid black;
  background: transparent;
  font-size: 1.5rem;
  padding: 8px;
  ::-webkit-datetime-edit-text { padding: 0 2rem; }
  ::-webkit-datetime-edit-month-field { text-transform: uppercase; }
  ::-webkit-datetime-edit-day-field { text-transform: uppercase; }
  ::-webkit-datetime-edit-year-field { text-transform: uppercase; }
  ::-webkit-inner-spin-button { display: none; }
  ::-webkit-calendar-picker-indicator { background: transparent;}
`

UnicodeDecodeError, invalid continuation byte

utf-8 code error usually comes when the range of numeric values exceeding 0 to 127.

the reason to raise this exception is:

1)If the code point is < 128, each byte is the same as the value of the code point. 2)If the code point is 128 or greater, the Unicode string can’t be represented in this encoding. (Python raises a UnicodeEncodeError exception in this case.)

In order to to overcome this we have a set of encodings, the most widely used is "Latin-1, also known as ISO-8859-1"

So ISO-8859-1 Unicode points 0–255 are identical to the Latin-1 values, so converting to this encoding simply requires converting code points to byte values; if a code point larger than 255 is encountered, the string can’t be encoded into Latin-1

when this exception occurs when you are trying to load a data set ,try using this format

df=pd.read_csv("top50.csv",encoding='ISO-8859-1')

Add encoding technique at the end of the syntax which then accepts to load the data set.

How to make git mark a deleted and a new file as a file move?

Do the move and the modify in separate commits.

c++ and opencv get and set pixel color to Mat

You did everything except copying the new pixel value back to the image.

This line takes a copy of the pixel into a local variable:

Vec3b color = image.at<Vec3b>(Point(x,y));

So, after changing color as you require, just set it back like this:

image.at<Vec3b>(Point(x,y)) = color;

So, in full, something like this:

Mat image = img;
for(int y=0;y<img.rows;y++)
{
    for(int x=0;x<img.cols;x++)
    {
        // get pixel
        Vec3b & color = image.at<Vec3b>(y,x);

        // ... do something to the color ....
        color[0] = 13;
        color[1] = 13;
        color[2] = 13;

        // set pixel
        //image.at<Vec3b>(Point(x,y)) = color;
        //if you copy value
    }
}

How do you programmatically set an attribute?

setattr(x, attr, 'magic')

For help on it:

>>> help(setattr)
Help on built-in function setattr in module __builtin__:

setattr(...)
    setattr(object, name, value)

    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ``x.y = v''.

Edit: However, you should note (as pointed out in a comment) that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.

The preferred way of creating a new element with jQuery

Much more expressive way,

jQuery('<div/>', {
    "id": 'foo',
    "name": 'mainDiv',
    "class": 'wrapper',
    "click": function() {
      jQuery(this).toggleClass("test");
    }}).appendTo('selector');

Reference: Docs

HTML form action and onsubmit issues

You should stop the submit procedure by returning false on the onsubmit callback.

<script>
    function checkRegistration(){
        if(!form_valid){
            alert('Given data is not correct');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()"...

Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:

<script>
    function checkRegistration(){
        var form_valid = (document.getElementById('some_input').value == 'google');
        if(!form_valid){
            alert('Given data is incorrect');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
    Write google to go to google...<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>

Warning: mysqli_query() expects parameter 1 to be mysqli, resource given

You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.

mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )

mysql $link generally means, the resource object of the established mysqli connection to query the database.

So there are two ways of solving this problem

mysqli_query();

$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql"); 
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));

Or, Using mysql_query() (This is now obselete)

$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");        
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());

As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .

Are Git forks actually Git clones?

In simplest terms,

When you say you are forking a repository, you are basically creating a copy of the original repository under your GitHub ID in your GitHub account.

and

When you say you are cloning a repository, you are creating a local copy of the original repository in your system (PC/laptop) directly without having a copy in your GitHub account.

submit a form in a new tab

It is also possible to use the new button attribute called formtarget that was introduced with HTML5.

<form>
  <input type="submit" formtarget="_blank"/>
</form>

File opens instead of downloading in internet explorer in a href link

It is known HTTP headers problem with Internet Explorer. Try to edit your server's .htaccess file (if you use Apache) and include the following rules:

# IE: force download of .xxx files
AddType application/octect-stream .xxx
<Files *.xxx>
  ForceType application/octet-stream
  Header Set Content-Disposition attachment
</Files>

Is Java a Compiled or an Interpreted programming language ?

Java is a byte-compiled language targeting a platform called the Java Virtual Machine which is stack-based and has some very fast implementations on many platforms.

How to get the screen width and height in iOS?

I've translated some of the above Objective-C answers into Swift code. Each translation is proceeded with a reference to the original answer.

Main Answer

let screen = UIScreen.main.bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height

##Simple Function Answer

func windowHeight() -> CGFloat {
    return UIScreen.main.bounds.size.height
}

func windowWidth() -> CGFloat {
    return UIScreen.main.bounds.size.width
}

##Device Orientation Answer

let screenHeight: CGFloat
let statusBarOrientation = UIApplication.shared.statusBarOrientation
// it is important to do this after presentModalViewController:animated:
if (statusBarOrientation != .portrait
    && statusBarOrientation != .portraitUpsideDown) {
    screenHeight = UIScreen.main.bounds.size.width
} else {
    screenHeight = UIScreen.main.bounds.size.height
}

##Log Answer

let screenWidth = UIScreen.main.bounds.size.width
let screenHeight = UIScreen.main.bounds.size.height
println("width: \(screenWidth)")
println("height: \(screenHeight)")

Set width of dropdown element in HTML select dropdown options

Small And Best One

#test{
width: 202px;
}
<select id="test" size="1" name="mrraja">

How to set page content to the middle of screen?

Solution for the code you posted:

.center{
    position:absolute;
    width:780px;
    height:650px;
    left:50%;
    top:50%;
    margin-left:-390px;
    margin-top:-325px;
}

<table class="center" width="780" border="0" align="center" cellspacing="2" bordercolor="#000000" bgcolor="#FFCC66">
      <tr>
        <td>
        <table width="100%" border="0">
      <tr>
        <td>
        <table width="100%" border="0">
        <tr>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
            <td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>        
        </tr>
        </table>
        </td>
      </tr>
      <tr>
        <td>
        <table width="100%" border="0">
        <tr>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
            <td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>        
        </tr>
        </table>
        </td>
      </tr>
</table>

--

How this works?

Example: http://jsfiddle.net/953Yj/

<div class="center">
    Lorem ipsum
</div>

.center{
    position:absolute;
    height: X px;
    width: Y px;
    left:50%;
    top:50%;
    margin-top:- X/2 px;
    margin-left:- Y/2 px;
}
  • X would your your height.
  • Y would be your width.

To position the div vertically and horizontally, divide X and Y by 2.

Creating a new empty branch for a new project

i found this help:

git checkout --orphan empty.branch.name
git rm --cached -r .
echo "init empty branch" > README.md
git add README.md
git commit -m "init empty branch"

"No rule to make target 'install'"... But Makefile exists

I was receiving the same error message, and my issue was that I was not in the correct directory when running the command make install. When I changed to the directory that had my makefile it worked.

So possibly you aren't in the right directory.

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

If you need a quick fix, simply add this before the line of your import:

// @ts-ignore

Clear the cache in JavaScript

Here's a snippet of what I'm using for my latest project.

From the controller:

if ( IS_DEV ) {
    $this->view->cacheBust = microtime(true);
} else {
    $this->view->cacheBust = file_exists($versionFile) 
        // The version file exists, encode it
        ? urlencode( file_get_contents($versionFile) )
        // Use today's year and week number to still have caching and busting 
        : date("YW");
}

From the view:

<script type="text/javascript" src="/javascript/somefile.js?v=<?= $this->cacheBust; ?>"></script>
<link rel="stylesheet" type="text/css" href="/css/layout.css?v=<?= $this->cacheBust; ?>">

Our publishing process generates a file with the revision number of the current build. This works by URL encoding that file and using that as a cache buster. As a fail-over, if that file doesn't exist, the year and week number are used so that caching still works, and it will be refreshed at least once a week.

Also, this provides cache busting for every page load while in the development environment so that developers don't have to worry with clearing the cache for any resources (javascript, css, ajax calls, etc).

java - iterating a linked list

I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):

  1. For Loop
  2. Enhanced For Loop
  3. While Loop
  4. Iterator
  5. Collections’s stream() util (Java8)

For loop

LinkedList<String> linkedList = new LinkedList<>();
System.out.println("==> For Loop Example.");
for (int i = 0; i < linkedList.size(); i++) {
    System.out.println(linkedList.get(i));
}

Enhanced for loop

for (String temp : linkedList) {
    System.out.println(temp);
}

While loop

int i = 0;
while (i < linkedList.size()) {
    System.out.println(linkedList.get(i));
    i++;
}

Iterator

Iterator<String> iterator = linkedList.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next()); 
}

collection stream() util (Java 8)

linkedList.forEach((temp) -> {
    System.out.println(temp);
});

One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i) operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.

Where does Git store files?

To be a bit more complete, Git works with:

  • the working tree (the root of which being where you made a git init)
  • "path to the Git repository" (where there is a .git, which will store the revisions of all your files)

GIT_DIR is an environment variable, which can be an absolute path or relative path to current working directory.

If it is not defined, the "path to the git repository" is by default at the root directory of your working tree (again, where you made a git init).

You can actually execute any Git command from anywhere from your disk, provided you specify the working tree path and the Git repository path:

git command --git-dir=<path> --work-tree=<path>

But if you execute them in one of the subdirectories of a Git repository (with no GIT-DIR or working tree path specified), Git will simply look in the current and parent directories until it find a .git, assume this it also the root directory of your working tree, and use that .git as the only container for all the revisions of your files.

Note: .git is also hidden in Windows (msysgit).
You would have to do a dir /AH to see it.
git 2.9 (June 2016) allows to configure that.


Note that Git 2.18 (Q2 2018) is starting the process to evolve how Git is storing objects, by refactoring the internal global data structure to make it possible to open multiple repositories, work with and then close them.

See commit 4a7c05f, commit 1fea63e (23 Mar 2018) by Jonathan Nieder (artagnon).
See commit bd27f50, commit ec7283e, commit d2607fa, commit a68377b, commit e977fc7, commit e35454f, commit 332295d, commit 2ba0bfd, commit fbe33e2, commit cf78ae4, commit 13068bf, commit 77f012e, commit 0b20903, commit 93d8d1e, commit ca5e6d2, commit cfc62fc, commit 13313fc, commit 9a00580 (23 Mar 2018) by Stefan Beller (stefanbeller).
(Merged by Junio C Hamano -- gitster -- in commit cf0b179, 11 Apr 2018)

repository: introduce raw object store field

The raw object store field will contain any objects needed for access to objects in a given repository.

This patch introduces the raw object store and populates it with the objectdir, which used to be part of the repository struct.

As the struct gains members, we'll also populate the function to clear the memory for these members.

In a later step, we'll introduce a struct object_parser, that will complement the object parsing in a repository struct:

  • The raw object parser is the layer that will provide access to raw object content,
  • while the higher level object parser code will parse raw objects and keeps track of parenthood and other object relationships using 'struct object'.

    For now only add the lower level to the repository struct.

Search code inside a Github project

While @VonC's answer works for some repositories, unfortunately for many repositories you can't right now. Github is simply not indexing them (as commented originally by @emddudley). They haven't stated this anywhere on their website, but they will tell you if you ask support:

From: Tim Pease
We have stopped adding newly pushed code into our codesearch index. The volume of code has outgrown our current search index, and we are working on moving to a more scalable search architecture. I'm sorry for the annoyance. We do not have an estimate for when this new search index will be up and running, but when it is ready a blog post will be published (https://github.com/blog).

Annoyingly there is no way to tell which repositories are not indexed other than the lack of results (which also could be from a bad query).

There also is no way to track this issue other than waiting for them to blog it (or watching here on SO).

From: Tim Pease
I am afraid our issue tracker is internal, but we can notify you as soon as the new search index is up and running.

Is arr.__len__() the preferred way to get the length of an array in Python?

you can use len(arr) as suggested in previous answers to get the length of the array. In case you want the dimensions of a 2D array you could use arr.shape returns height and width

Select second last element with css

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.


The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

_x000D_
_x000D_
#container :nth-last-child(-n+2) {
  background-color: cyan;
}
_x000D_
<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>
_x000D_
_x000D_
_x000D_

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

Meaning of Choreographer messages in Logcat

This if an Info message that could pop in your LogCat on many situations.

In my case, it happened when I was inflating several views from XML layout files programmatically. The message is harmless by itself, but could be the sign of a later problem that would use all the RAM your App is allowed to use and cause the mega-evil Force Close to happen. I have grown to be the kind of Developer that likes to see his Log WARN/INFO/ERROR Free. ;)

So, this is my own experience:

I got the message:

10-09 01:25:08.373: I/Choreographer(11134): Skipped XXX frames!  The application may be doing too much work on its main thread.

... when I was creating my own custom "super-complex multi-section list" by inflating a view from XML and populating its fields (images, text, etc...) with the data coming from the response of a REST/JSON web service (without paging capabilities) this views would act as rows, sub-section headers and section headers by adding all of them in the correct order to a LinearLayout (with vertical orientation inside a ScrollView). All of that to simulate a listView with clickable elements... but well, that's for another question.

As a responsible Developer you want to make the App really efficient with the system resources, so the best practice for lists (when your lists are not so complex) is to use a ListActivity or ListFragment with a Loader and fill the ListView with an Adapter, this is supposedly more efficient, in fact it is and you should do it all the time, again... if your list is not so complex.

Solution: I implemented paging on my REST/JSON web service to prevent "big response sizes" and I wrapped the code that added the "rows", "section headers" and "sub-section headers" views on an AsyncTask to keep the Main Thread cool.

So... I hope my experience helps someone else that is cracking their heads open with this Info message.

Happy hacking!

Set Focus on EditText

Just put this line on your onCreate()

editText.requestFocus();

Find a string by searching all tables in SQL Server Management Studio 2008

A bit late but hopefully useful.

Why not try some of the third party tools that can be integrated into SSMS.

I’ve worked with ApexSQL Search (100% free) with good success for both schema and data search and there is also SSMS tools pack that has this feature (not free for SQL 2012 but quite affordable).

Stored procedure above is really great; it’s just that this is way more convenient in my opinion. Also, it would require some slight modifications if you want to search for datetime columns or GUID columns and such…

How do I wrap text in a pre tag?

The <pre>-Element stands for "pre-formatted-text" and is intended to keep the formatting of the text (or whatever) between its tags. Therefore it is actually not inteded to have automatic word-wrapping or line-breaks within the <pre>-Tag

Text in a element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks.

source: w3schools.com, emphasises made by myself.

Jenkins fails when running "service start jenkins"

I had the same issue, and when I checked if Java is installed I realised it's not, so installing Java solved the problem for me.

Check for java:

java -version

If Java is installed in the system, the command will return the java version otherwise it will show a message like this.

The program 'java' can be found in the following packages:
 * default-jre
 * gcj-5-jre-headless
 * openjdk-8-jre-headless
 * gcj-4.8-jre-headless
 * gcj-4.9-jre-headless
 * openjdk-9-jre-headless

To install java use the following command.

sudo apt-get install default-jre

Find commit by hash SHA in Git

There are two ways to do this.

1. providing the SHA of the commit you want to see to git log

git log -p a2c25061

Where -p is short for patch

2. use git show

git show a2c25061

The output for both commands will be:

  • the commit
  • the author
  • the date
  • the commit message
  • the patch information

Angularjs - simple form submit

_x000D_
_x000D_
var app = angular.module( "myApp", [] );_x000D_
_x000D_
app.controller( "myCtrl", ["$scope", function($scope) {_x000D_
_x000D_
    $scope.submit_form = function(formData) {_x000D_
_x000D_
        $scope.formData = formData;_x000D_
_x000D_
        console.log(formData); // object_x000D_
        console.log(JSON.stringify(formData)); // string_x000D_
_x000D_
        $scope.form = {}; // clear ng-model form_x000D_
_x000D_
    }_x000D_
_x000D_
}] );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="myCtrl">_x000D_
_x000D_
    <form ng-submit="submit_form(form)" >_x000D_
_x000D_
        Firstname: <input type="text" ng-model="form.firstname" /><br />_x000D_
        Lastname: <input type="text" ng-model="form.lastname" /><br />_x000D_
_x000D_
        <hr />_x000D_
_x000D_
        <input type="submit" value="Submit" />_x000D_
_x000D_
    </form>_x000D_
_x000D_
    <hr />          _x000D_
_x000D_
    <p>Firstname: {{ form.firstname }}</p>_x000D_
    <p>Lastname: {{ form.lastname }}</p>_x000D_
_x000D_
    <pre>Submit Form: {{ formData }} </pre>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen

Initial bytes incorrect after Java AES/CBC decryption

The IV that your using for decryption is incorrect. Replace this code

//Decrypt cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);

With this code

//Decrypt cipher
Cipher decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
IvParameterSpec ivParameterSpec = new IvParameterSpec(encryptCipher.getIV());
decryptCipher.init(Cipher.DECRYPT_MODE, aesKey, ivParameterSpec);

And that should solve your problem.


Below includes an example of a simple AES class in Java. I do not recommend using this class in production environments, as it may not account for all of the specific needs of your application.

import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AES 
{
    public static byte[] encrypt(final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
    {       
        return AES.transform(Cipher.ENCRYPT_MODE, keyBytes, ivBytes, messageBytes);
    }

    public static byte[] decrypt(final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
    {       
        return AES.transform(Cipher.DECRYPT_MODE, keyBytes, ivBytes, messageBytes);
    }

    private static byte[] transform(final int mode, final byte[] keyBytes, final byte[] ivBytes, final byte[] messageBytes) throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        final SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
        final IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        byte[] transformedBytes = null;

        try
        {
            final Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

            cipher.init(mode, keySpec, ivSpec);

            transformedBytes = cipher.doFinal(messageBytes);
        }        
        catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) 
        {
            e.printStackTrace();
        }
        return transformedBytes;
    }

    public static void main(final String[] args) throws InvalidKeyException, InvalidAlgorithmParameterException
    {
        //Retrieved from a protected local file.
        //Do not hard-code and do not version control.
        final String base64Key = "ABEiM0RVZneImaq7zN3u/w==";

        //Retrieved from a protected database.
        //Do not hard-code and do not version control.
        final String shadowEntry = "AAECAwQFBgcICQoLDA0ODw==:ZtrkahwcMzTu7e/WuJ3AZmF09DE=";

        //Extract the iv and the ciphertext from the shadow entry.
        final String[] shadowData = shadowEntry.split(":");        
        final String base64Iv = shadowData[0];
        final String base64Ciphertext = shadowData[1];

        //Convert to raw bytes.
        final byte[] keyBytes = Base64.getDecoder().decode(base64Key);
        final byte[] ivBytes = Base64.getDecoder().decode(base64Iv);
        final byte[] encryptedBytes = Base64.getDecoder().decode(base64Ciphertext);

        //Decrypt data and do something with it.
        final byte[] decryptedBytes = AES.decrypt(keyBytes, ivBytes, encryptedBytes);

        //Use non-blocking SecureRandom implementation for the new IV.
        final SecureRandom secureRandom = new SecureRandom();

        //Generate a new IV.
        secureRandom.nextBytes(ivBytes);

        //At this point instead of printing to the screen, 
        //one should replace the old shadow entry with the new one.
        System.out.println("Old Shadow Entry      = " + shadowEntry);
        System.out.println("Decrytped Shadow Data = " + new String(decryptedBytes, StandardCharsets.UTF_8));
        System.out.println("New Shadow Entry      = " + Base64.getEncoder().encodeToString(ivBytes) + ":" + Base64.getEncoder().encodeToString(AES.encrypt(keyBytes, ivBytes, decryptedBytes)));
    }
}

Note that AES has nothing to do with encoding, which is why I chose to handle it separately and without the need of any third party libraries.

How to open in default browser in C#

dotnet core throws an error if we use Process.Start(URL). The following code will work in dotnet core. You can add any browser instead of Chrome.

var processes = Process.GetProcessesByName("Chrome");
var path  = processes.FirstOrDefault()?.MainModule?.FileName;
Process.Start(path,  url);

Newline in string attribute

I realize this is on older question but just wanted to add that

Environment.NewLine

also works if doing this through code.

Razor View Without Layout

Do you have a _ViewStart.cshtml in this directory? I had the same problem you're having when I tried using _ViewStart. Then I renamed it _mydefaultview, moved it to the Views/Shared directory, and switched to specifying no view in cshtml files where I don't want it, and specifying _mydefaultview for the rest. Don't know why this was necessary, but it worked.

Difference between static class and singleton pattern?

static classes usually are used for libraries, singletons are used if I need only one instance of a particular class. From the point of view of memory there are some differences though: usually in the heap there are allocated only objects, the only methods allocated are methods that are current running. a static class has all methods static too and that will be in the heap from begin, so in general the static class consume more memory.

How to convert an integer to a string in any base?

Surprisingly, people were giving only solutions that convert to small bases (smaller than the length of the English alphabet). There was no attempt to give a solution which converts to any arbitrary base from 2 to infinity.

So here is a super simple solution:

def numberToBase(n, b):
    if n == 0:
        return [0]
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

so if you need to convert some super huge number to the base 577,

numberToBase(67854 ** 15 - 102, 577), will give you a correct solution: [4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455],

Which you can later convert to any base you want

Set max-height on inner div so scroll bars appear, but not on parent div

set this :

#inner-right {
    height: 100%;
    max-height: 96%;//change here
    overflow: auto;
    background: ivory;
}

this will solve your problem.

How can I display a tooltip message on hover using jQuery?

take a look at the jQuery Tooltip plugin. You can pass in an options object for different options.

There are also other alternative tooltip plugins available, of which a few are

Take look at the demos and documentation and please update your question if you have specific questions about how to use them in your code.

What is the best way to remove the first element from an array?

You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:

  1. Shift every element up one, then set the last element to null.
  2. Create a new array, then copy it.

You can use System.arraycopy for either of these. Both of these are O(n), since they copy all but 1 element.

If you will be removing the first element often, consider using LinkedList instead. You can use LinkedList.remove, which is from the Queue interface, for convenience. With LinkedList, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator to that position. However, accessing an arbitrary element by index is O(n).

How can I remove jenkins completely from linux

if you are ubuntu user than try this:

sudo apt-get remove jenkins
sudo apt-get remove --auto-remove jenkins

'apt-get remove' command is use to remove package.

Retrofit 2: Get JSON from Response body

A better approach is to let Retrofit generate POJO for you from the json (using gson). First thing is to add .addConverterFactory(GsonConverterFactory.create()) when creating your Retrofit instance. For example, if you had a User java class (such as shown below) that corresponded to your json, then your retrofit api could return Call<User>

class User {
    private String id;
    private String Username;
    private String Level;
    ...
}    

How to set a Header field on POST a form?

To add into every ajax request, I have answered it here: https://stackoverflow.com/a/58964440/1909708


To add into particular ajax requests, this' how I implemented:

var token_value = $("meta[name='_csrf']").attr("content");
var token_header = $("meta[name='_csrf_header']").attr("content");
$.ajax("some-endpoint.do", {
 method: "POST",
 beforeSend: function(xhr) {
  xhr.setRequestHeader(token_header, token_value);
 },
 data: {form_field: $("#form_field").val()},
 success: doSomethingFunction,
 dataType: "json"
});

You must add the meta elements in the JSP, e.g.

<html>
<head>        
    <!-- default header name is X-CSRF-TOKEN -->
    <meta name="_csrf_header" content="${_csrf.headerName}"/>
    <meta name="_csrf" content="${_csrf.token}"/>

To add to a form submission (synchronous) request, I have answered it here: https://stackoverflow.com/a/58965526/1909708

Creating InetAddress object in Java

InetAddress.getByName also works for ip address.

From the JavaDoc

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

DISABLE the Horizontal Scroll

So to fix this properly, I did what others here did and used css to get hide the horizontal toolbar:

.name {
  max-width: 100%;
  overflow-x: hidden;
}

Then in js, I created an event listener to look for scrolling, and counteracted the users attempted horizontal scroll.

var scrollEventHandler = function()
{
  window.scroll(0, window.pageYOffset)
}

window.addEventListener("scroll", scrollEventHandler, false);

I saw somebody do something similar, but apparently that didn't work. This however is working perfectly fine for me.

Regex: Use start of line/end of line signs (^ or $) in different context

Just use look-arounds to solve this:

(?<=^|,)garp(?=$|,)

The difference with look-arounds and just regular groups are that with regular groups the comma would be part of the match, and with look-arounds it wouldn't. In this case it doesn't make a difference though.

Oracle DB: How can I write query ignoring case?

In version 12.2 and above, the simplest way to make the query case insensitive is this:

SELECT * FROM TABLE WHERE TABLE.NAME COLLATE BINARY_CI Like 'IgNoReCaSe'

Keyboard shortcut to comment lines in Sublime Text 2

In my keyboard (Swedish) it´s the key to the right of "ä": "*".

ctrl+*

Laravel migration table field's type change

update: 31 Oct 2018, Still usable on laravel 5.7 https://laravel.com/docs/5.7/migrations#modifying-columns

To make some change to existing db, you can modify column type by using change() in migration.

This is what you could do

Schema::table('orders', function ($table) {
    $table->string('category_id')->change();
});

please note you need to add doctrine/dbal dependency to composer.json for more information you can find it here http://laravel.com/docs/5.1/migrations#modifying-columns

php: how to get associative array key from numeric index?

If you only plan to work with one key in particular, you may accomplish this with a single line without having to store an array for all of the keys:

echo array_keys($array)[$i];

Copy rows from one table to another, ignoring duplicates

DISTINCT is the keyword you're looking for.

In MSSQL, copying unique rows from a table to another can be done like this:

SELECT DISTINCT column_name
INTO newTable
FROM srcTable

The column_name is the column you're searching the unique values from.

Tested and works.

Remote Connections Mysql Ubuntu

MySQL only listens to localhost, if we want to enable the remote access to it, then we need to made some changes in my.cnf file:

sudo nano /etc/mysql/my.cnf

We need to comment out the bind-address and skip-external-locking lines:

#bind-address = 127.0.0.1
# skip-external-locking

After making these changes, we need to restart the mysql service:

sudo service mysql restart

How to get an enum value from a string value in Java?

If you don't want to write your own utility use Google's library:

Enums.getIfPresent(Blah.class, "A")

Unlike the built in java function it let's you check if A is present in Blah and doesn't throw an exception.

How can I create tests in Android Studio?

Android Studio has been kind of a moving target, first being a developer preview and now being in beta. The path for the Test classes in the project has changed during time, but no matter what version of AS you are using, the path is declared in your .iml file. Currently, with version 0.8.3, you'll find the following inside the inner iml file:

      <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
  <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
  <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
  <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
  <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
  <sourceFolder url="file://$MODULE_DIR$/src/androidTest/groovy" isTestSource="true" />
  <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
  <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />

The .iml file is telling you where to place your test classes.

How to set a radio button in Android

For radioButton use

radio1.setChecked(true);

It does not make sense to have just one RadioButton. If you have more of them you need to uncheck others through

radio2.setChecked(false); ...

If your setting is just on/off use CheckBox.

Hadoop cluster setup - java.net.ConnectException: Connection refused

In /etc/hosts:

  1. Add this line:

your-ip-address your-host-name

example: 192.168.1.8 master

In /etc/hosts:

  1. Delete the line with 127.0.1.1 (This will cause loopback)

  2. In your core-site, change localhost to your-ip or your-hostname

Now, restart the cluster.

How to start an Intent by passing some parameters to it?

putExtra() : This method sends the data to another activity and in parameter, we have to pass key-value pair.

Syntax: intent.putExtra("key", value);

Eg: intent.putExtra("full_name", "Vishnu Sivan");

Intent intent=getIntent() : It gets the Intent from the previous activity.

fullname = intent.getStringExtra(“full_name”) : This line gets the string form previous activity and in parameter, we have to pass the key which we have mentioned in previous activity.

Sample Code:

Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("firstName", "Vishnu");
intent.putExtra("lastName", "Sivan");
startActivity(intent);

Does --disable-web-security Work In Chrome Anymore?

Just create this batch file and run it on windows. It basically would kill all chrome instances and then would start chrome with disabling security. Save the following script in batch file say ***.bat and double click on it.

TASKKILL /F /IM chrome.exe
start chrome.exe --args --disable-web-security –-allow-file-access-from-files

How to Sort Date in descending order From Arraylist Date in android?

Just add like this in case 1: like this

 case 0:
     list = DBAdpter.requestUserData(assosiatetoken);
     Collections.sort(list, byDate);
     for (int i = 0; i < list.size(); i++) {
         if (list.get(i).lastModifiedDate != null) {
             lv.setAdapter(new MyListAdapter(
                     getApplicationContext(), list));
         }
     }
     break;

and put this method at end of the your class

static final Comparator<All_Request_data_dto> byDate = new Comparator<All_Request_data_dto>() {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");

    public int compare(All_Request_data_dto ord1, All_Request_data_dto ord2) {
        Date d1 = null;
        Date d2 = null;
        try {
            d1 = sdf.parse(ord1.lastModifiedDate);
            d2 = sdf.parse(ord2.lastModifiedDate);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        return (d1.getTime() > d2.getTime() ? -1 : 1);     //descending
    //  return (d1.getTime() > d2.getTime() ? 1 : -1);     //ascending
    }
};

HTML 5 Video "autoplay" not automatically starting in CHROME

Try this when i tried giving muted , check this demo in codpen

    <video width="320" height="240" controls autoplay muted id="videoId">
  <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
  Your browser does not support the video tag.
</video>

script

function toggleMute() {

  var video=document.getElementById("videoId");

  if(video.muted){
    video.muted = false;
  } else {
    debugger;
    video.muted = true;
    video.play()
  }

}

$(document).ready(function(){
  setTimeout(toggleMute,3000);
})

edited attribute content

autoplay muted playsinline

https://developers.google.com/web/updates/2017/09/autoplay-policy-changes

Purpose of Unions in C and C++

For one more example of the actual use of unions, the CORBA framework serializes objects using the tagged union approach. All user-defined classes are members of one (huge) union, and an integer identifier tells the demarshaller how to interpret the union.

How to delete columns in pyspark dataframe

You can use two way:

1: You just keep the necessary columns:

drop_column_list = ["drop_column"]
df = df.select([column for column in df.columns if column not in drop_column_list])  

2: This is the more elegant way.

df = df.drop("col_name")

You should avoid the collect() version, because it will send to the master the complete dataset, it will take a big computing effort!

How to disable a ts rule for a specific line?

You can use /* tslint:disable-next-line */ to locally disable tslint. However, as this is a compiler error disabling tslint might not help.

You can always temporarily cast $ to any:

delete ($ as any).summernote.options.keyMap.pc.TAB

which will allow you to access whatever properties you want.


Edit: As of Typescript 2.6, you can now bypass a compiler error/warning for a specific line:

if (false) {
    // @ts-ignore: Unreachable code error
    console.log("hello");
}

Note that the official docs "recommend you use [this] very sparingly". It is almost always preferable to cast to any instead as that better expresses intent.

Select a random sample of results from a query result

Suppose you are trying to select exactly 1,000 random rows from a table called my_table. This is one way to do it:

select
    *
from
    (
        select
            row_number() over(order by dbms_random.value) as random_id,
            x.*
        from
            my_table x
    )
where
    random_id <= 1000
;

This is a slight deviation from the answer posted by @Quassnoi. They both have the same costs and execution times. The only difference is that you can select the random number used to fetch the sample.

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Change icon on click (toggle)

$("#togglebutton").click(function () {
  $(".fa-arrow-circle-left").toggleClass("fa-arrow-circle-right");
}

I have a button with the id "togglebutton" and an icon from FontAwesome . This can be a way to toggle it . from left arrow to right arrow icon

Android M Permissions: onRequestPermissionsResult() not being called

This issue was actually being caused by NestedFragments. Basically most fragments we have extend a HostedFragment which in turn extends a CompatFragment. Having these nested fragments caused issues which eventually were solved by another developer on the project.

He was doing some low level stuff like bit switching to get this working so I'm not too sure of the actual final solution

MySQL with Node.js

node-mysql is probably one of the best modules out there used for working with MySQL database which is actively maintained and well documented.

Java String to SHA1

The reason this doesn't work is that when you call String(md.digest(convertme)), you are telling Java to interpret a sequence of encrypted bytes as a String. What you want is to convert the bytes into hexadecimal characters.

Equivalent function for DATEADD() in Oracle

Not my answer :

I wasn't too happy with the answers above and some additional searching yielded this :

SELECT SYSDATE AS current_date,

       SYSDATE + 1 AS plus_1_day,

       SYSDATE + 1/24 AS plus_1_hours,

       SYSDATE + 1/24/60 AS plus_1_minutes,

       SYSDATE + 1/24/60/60 AS plus_1_seconds

FROM   dual;

which I found very helpful. From http://sqlbisam.blogspot.com/2014/01/add-date-interval-to-date-or-dateadd.html

Check if an object exists

You can also use get_object_or_404(), it will raise a Http404 if the object wasn't found:

user_pass = log_in(request.POST) #form class
if user_pass.is_valid():
    cleaned_info = user_pass.cleaned_data
    user_object = get_object_or_404(User, email=cleaned_info['username'])
    # User object found, you are good to go!
    ...

ValueError: unsupported format character while forming strings

For anyone checking this using python 3:

If you want to print the following output "100% correct":

python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")


A neat programming workaround for compatibility across diff versions of python is shown below:

Note: If you have to use this, you're probably experiencing many other errors... I'd encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.

DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.

import sys

if version_info.major==3:
    if version_info.minor>=8:
        my_string = "100% correct"
    else:
        my_string = "100%% correct"

# Finally
print(my_string)

Global Variable from a different file Python

When you write

from file2 import *

it actually copies the names defined in file2 into the namespace of file1. So if you reassign those names in file1, by writing

foo = "bar"

for example, it will only make that change in file1, not file2. Note that if you were to change an attribute of foo, say by doing

foo.blah = "bar"

then that change would be reflected in file2, because you are modifying the existing object referred to by the name foo, not replacing it with a new object.

You can get the effect you want by doing this in file1.py:

import file2
file2.foo = "bar"
test = SomeClass()

(note that you should delete from foo import *) although I would suggest thinking carefully about whether you really need to do this. It's not very common that changing one module's variables from within another module is really justified.

Count length of array and return 1 if it only contains one element

Maybe I am missing something (lots of many-upvotes-members answers here that seem to be looking at this different to I, which would seem implausible that I am correct), but length is not the correct terminology for counting something. Length is usually used to obtain what you are getting, and not what you are wanting.

$cars.count should give you what you seem to be looking for.

"Primary Filegroup is Full" in SQL Server 2008 Standard for no apparent reason

OK, got it working. Turns out that an NTFS volume where the DB files were located got heavily fragmented. Stopped SQL Server, defragmented the whole thing and all it was fine ever since.

What is the difference between UTF-8 and ISO-8859-1?

One more important thing to realise: if you see iso-8859-1, it probably refers to Windows-1252 rather than ISO/IEC 8859-1. They differ in the range 0x80–0x9F, where ISO 8859-1 has the C1 control codes, and Windows-1252 has useful visible characters instead.

For example, ISO 8859-1 has 0x85 as a control character (in Unicode, U+0085, ``), while Windows-1252 has a horizontal ellipsis (in Unicode, U+2026 HORIZONTAL ELLIPSIS, ).

The WHATWG Encoding spec (as used by HTML) expressly declares iso-8859-1 to be a label for windows-1252, and web browsers do not support ISO 8859-1 in any way: the HTML spec says that all encodings in the Encoding spec must be supported, and no more.

Also of interest, HTML numeric character references essentially use Windows-1252 for 8-bit values rather than Unicode code points; per https://html.spec.whatwg.org/#numeric-character-reference-end-state, &#x85; will produce U+2026 rather than U+0085.

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

Are you import them? Like this:

compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:recyclerview-v7:21.0.3'

Generating (pseudo)random alpha-numeric strings

1 line:

$FROM = 0; $TO = 'zzzz';
$code = base_convert(rand( $FROM ,base_convert( $TO , 36,10)),10,36);
echo $code;

I want to load another HTML page after a specific amount of time

<script>
    setTimeout(function(){
        window.location.href = 'form2.html';
    }, 5000);
</script>

And for home page add only '/'

<script>
    setTimeout(function(){
        window.location.href = '/';
    }, 5000);
</script>

How do I create a Bash alias?

In my .bashrc file the following lines were there by default:

# Alias definitions.
# You may want to put all your additions into a separate file like
# ~/.bash_aliases, instead of adding them here directly.
# See /usr/share/doc/bash-doc/examples in the bash-doc package.

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

Hence, in my platform .bash_aliases is the file used for aliases by default (and the one I use). I'm not an OS X user, but I guess that if you open your .bashrc file, you'll be able to identify what's the file commonly used for aliases in your platform.

JQuery Ajax POST in Codeigniter

    <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class UserController extends CI_Controller {

        public function verifyUser()    {
            $userName =  $_POST['userName'];
            $userPassword =  $_POST['userPassword'];
            $status = array("STATUS"=>"false");
            if($userName=='admin' && $userPassword=='admin'){
                $status = array("STATUS"=>"true");  
            }
            echo json_encode ($status) ;    
        }
    }


function makeAjaxCall(){
    $.ajax({
        type: "post",
        url: "http://localhost/CodeIgnitorTutorial/index.php/usercontroller/verifyUser",
        cache: false,               
        data: $('#userForm').serialize(),
        success: function(json){                        
        try{        
            var obj = jQuery.parseJSON(json);
            alert( obj['STATUS']);


        }catch(e) {     
            alert('Exception while request..');
        }       
        },
        error: function(){                      
            alert('Error while request..');
        }
 });
}

IIS Config Error - This configuration section cannot be used at this path

Most IIS sections are locked by default but you can "unlock" them by setting the attribute overrideModeDefault from "Deny" to "Allow" for the relevant section group by modifying the ApplicationHost.config file located in %windir%\system32\inetsrv\config in Administrator mode

enter image description here

How can I remove the first line of a text file using bash/sed script?

As Pax said, you probably aren't going to get any faster than this. The reason is that there are almost no filesystems that support truncating from the beginning of the file so this is going to be an O(n) operation where n is the size of the file. What you can do much faster though is overwrite the first line with the same number of bytes (maybe with spaces or a comment) which might work for you depending on exactly what you are trying to do (what is that by the way?).

Xcode: failed to get the task for process

To anyone who comes across this: After reading this, I attempted to solve the problem by setting the Debug signing to my Development certificate only to find that deployment was still failing.

Turns out my target was Release and therefore still signing with the distribution certificate - either go back to Debug target or change the release signing to Development temporarily.

how to implement login auth in node.js

_x000D_
_x000D_
======authorization====== MIDDLEWARE_x000D_
_x000D_
const jwt = require('../helpers/jwt')_x000D_
const User = require('../models/user')_x000D_
_x000D_
module.exports = {_x000D_
  authentication: function(req, res, next) {_x000D_
    try {_x000D_
      const user = jwt.verifyToken(req.headers.token, process.env.JWT_KEY)_x000D_
      User.findOne({ email: user.email }).then(result => {_x000D_
        if (result) {_x000D_
          req.body.user = result_x000D_
          req.params.user = result_x000D_
          next()_x000D_
        } else {_x000D_
          throw new Error('User not found')_x000D_
        }_x000D_
      })_x000D_
    } catch (error) {_x000D_
      console.log('langsung dia masuk sini')_x000D_
_x000D_
      next(error)_x000D_
    }_x000D_
  },_x000D_
_x000D_
  adminOnly: function(req, res, next) {_x000D_
    let loginUser = req.body.user_x000D_
    if (loginUser && loginUser.role === 'admin') {_x000D_
      next()_x000D_
    } else {_x000D_
      next(new Error('Not Authorized'))_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
====error handler==== MIDDLEWARE_x000D_
const errorHelper = require('../helpers/errorHandling')_x000D_
_x000D_
module.exports = function(err, req, res, next) {_x000D_
  //   console.log(err)_x000D_
  let errorToSend = errorHelper(err)_x000D_
  // console.log(errorToSend)_x000D_
  res.status(errorToSend.statusCode).json(errorToSend)_x000D_
}_x000D_
_x000D_
_x000D_
====error handling==== HELPER_x000D_
var nodeError = ["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"]_x000D_
var mongooseError = ["MongooseError","DisconnectedError","DivergentArrayError","MissingSchemaError","DocumentNotFoundError","MissingSchemaError","ObjectExpectedError","ObjectParameterError","OverwriteModelError","ParallelSaveError","StrictModeError","VersionError"]_x000D_
var mongooseErrorFromClient = ["CastError","ValidatorError","ValidationError"];_x000D_
var jwtError = ["TokenExpiredError","JsonWebTokenError","NotBeforeError"]_x000D_
_x000D_
function nodeErrorMessage(message){_x000D_
    switch(message){_x000D_
        case "Token is undefined":{_x000D_
            return 403;_x000D_
        }_x000D_
        case "User not found":{_x000D_
            return 403;_x000D_
        }_x000D_
        case "Not Authorized":{_x000D_
            return 401;_x000D_
        }_x000D_
        case "Email is Invalid!":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Password is Invalid!":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Incorrect password for register as admin":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Item id not found":{_x000D_
            return 400;_x000D_
        }_x000D_
        case "Email or Password is invalid": {_x000D_
            return 400_x000D_
        }_x000D_
        default :{_x000D_
            return 500;_x000D_
        }_x000D_
    }_x000D_
}_x000D_
_x000D_
module.exports = function(errorObject){_x000D_
    // console.log("===ERROR OBJECT===")_x000D_
    // console.log(errorObject)_x000D_
    // console.log("===ERROR STACK===")_x000D_
    // console.log(errorObject.stack);_x000D_
_x000D_
    let statusCode = 500;  _x000D_
    let returnObj = {_x000D_
        error : errorObject_x000D_
    }_x000D_
    if(jwtError.includes(errorObject.name)){_x000D_
        statusCode = 403;_x000D_
        returnObj.message = "Token is Invalid"_x000D_
        returnObj.source = "jwt"_x000D_
    }_x000D_
    else if(nodeError.includes(errorObject.name)){_x000D_
        returnObj.error = JSON.parse(JSON.stringify(errorObject, ["message", "arguments", "type", "name"]))_x000D_
        returnObj.source = "node";_x000D_
        statusCode = nodeErrorMessage(errorObject.message);_x000D_
        returnObj.message = errorObject.message;_x000D_
    }else if(mongooseError.includes(errorObject.name)){_x000D_
        returnObj.source = "database"_x000D_
        returnObj.message = "Error from server"_x000D_
    }else if(mongooseErrorFromClient.includes(errorObject.name)){_x000D_
        returnObj.source = "database";_x000D_
        errorObject.message ? returnObj.message = errorObject.message : returnObj.message = "Bad Request"_x000D_
        statusCode = 400;_x000D_
    }else{_x000D_
        returnObj.source = "unknown error";_x000D_
        returnObj.message = "Something error";_x000D_
    }_x000D_
    returnObj.statusCode = statusCode;_x000D_
    _x000D_
    return returnObj;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
===jwt====_x000D_
const jwt = require('jsonwebtoken')_x000D_
_x000D_
function generateToken(payload) {_x000D_
    let token = jwt.sign(payload, process.env.JWT_KEY)_x000D_
    return token_x000D_
}_x000D_
_x000D_
function verifyToken(token) {_x000D_
    let payload = jwt.verify(token, process.env.JWT_KEY)_x000D_
    return payload_x000D_
}_x000D_
_x000D_
module.exports = {_x000D_
    generateToken, verifyToken_x000D_
}_x000D_
_x000D_
===router index===_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
_x000D_
// router.get('/', )_x000D_
router.use('/users', require('./users'))_x000D_
router.use('/products', require('./product'))_x000D_
router.use('/transactions', require('./transaction'))_x000D_
_x000D_
module.exports = router_x000D_
_x000D_
====router user ====_x000D_
const express = require('express')_x000D_
const router = express.Router()_x000D_
const User = require('../controllers/userController')_x000D_
const auth = require('../middlewares/auth')_x000D_
_x000D_
/* GET users listing. */_x000D_
router.post('/register', User.register)_x000D_
router.post('/login', User.login)_x000D_
router.get('/', auth.authentication, User.getUser)_x000D_
router.post('/logout', auth.authentication, User.logout)_x000D_
module.exports = router_x000D_
_x000D_
_x000D_
====app====_x000D_
require('dotenv').config()_x000D_
const express = require('express')_x000D_
const cookieParser = require('cookie-parser')_x000D_
const logger = require('morgan')_x000D_
const cors = require('cors')_x000D_
const indexRouter = require('./routes/index')_x000D_
const errorHandler = require('./middlewares/errorHandler')_x000D_
const mongoose = require('mongoose')_x000D_
const app = express()_x000D_
_x000D_
mongoose.connect(process.env.DB_URI, {_x000D_
  useNewUrlParser: true,_x000D_
  useUnifiedTopology: true,_x000D_
  useCreateIndex: true,_x000D_
  useFindAndModify: false_x000D_
})_x000D_
_x000D_
app.use(cors())_x000D_
app.use(logger('dev'))_x000D_
app.use(express.json())_x000D_
app.use(express.urlencoded({ extended: false }))_x000D_
app.use(cookieParser())_x000D_
_x000D_
app.use('/', indexRouter)_x000D_
app.use(errorHandler)_x000D_
_x000D_
module.exports = app
_x000D_
_x000D_
_x000D_

annotation to make a private method public only for test classes

Okay, so here we have two things that are being mixed. First thing, is when you need to mark something to be used only on test, which I agree with @JB Nizet, using the guava annotation would be good.

A different thing, is to test private methods. Why should you test private methods from the outside? I mean.. You should be able to test the object by their public methods, and at the end that its behavior. At least, that we are doing and trying to teach to junior developers, that always try to test private methods (as a good practice).

Converting VS2012 Solution to VS2010

Solution of VS2010 is supported by VS2012. Solution of VS2012 isn't supported by VS2010 --> one-way upgrade only. VS2012 doesn't support setup projects. Find here more about VS2010/VS2012 compatibility: http://msdn.microsoft.com/en-us/library/hh266747(v=vs.110).aspx

How to use a variable inside a regular expression?

I find it very convenient to build a regular expression pattern by stringing together multiple smaller patterns.

import re

string = "begin:id1:tag:middl:id2:tag:id3:end"
re_str1 = r'(?<=(\S{5})):'
re_str2 = r'(id\d+):(?=tag:)'
re_pattern = re.compile(re_str1 + re_str2)
match = re_pattern.findall(string)
print(match)

Output:

[('begin', 'id1'), ('middl', 'id2')]

Refresh or force redraw the fragment

detach().detach() not working after support library update 25.1.0 (may be earlier). This solution works fine after update:

getSupportFragmentManager()
    .beginTransaction()
    .detach(oldFragment)
    .commitNowAllowingStateLoss();

getSupportFragmentManager()
    .beginTransaction()
    .attach(oldFragment)
    .commitAllowingStateLoss();

Can't use WAMP , port 80 is used by IIS 7.5

This could also be an issue of port 80 being used by "Web Deployment Agent Service". you can stop it from administrative tools->services and free up that port. as shown here

Recover SVN password from local cache

In ~/.subversion/auth/svn.simple/ you should find a file with a long hexadecimal name. The password is in there in plaintext.

If there is more than one file you'll need to find that one that references the server you need the password for.

TypeError: 'list' object is not callable in python

In the league of stupid Monday morning mistakes, using round brackets instead of square brackets when trying to access an item in the list will also give you the same error message:

l=[1,2,3]

print(l[2])#GOOD
print(l(2))#BAD

TypeError: 'list' object is not callable

How to remove time portion of date in C# in DateTime object only?

In case you would want to use Binding and show only Date portion without time

ToolTip="{Binding TransactionModel.TransactionDate, StringFormat=d}"

How to make PDF file downloadable in HTML link?

This can be achieved using HTML.

<a href="myfile.pdf">Download Brochure</a>

Add download attribute to it: Here the file name will be myfile.pdf

<a href="myfile.pdf" download>Download Brochure</a>

Specify a value for the download attribute:

<a href="myfile.pdf" download="Brochure">Download Brochure</a>

Here the file name will be Brochure.pdf

Breaking out of nested loops

If you're going to raise an exception, you might raise a StopIteration exception. That will at least make the intent obvious.

Using an Alias in a WHERE clause

Or you can have your alias in a HAVING clause

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

It looks like, cargo can have one or more item. Each item would have a reference to its corresponding cargo.

From the log, item object is inserted first and then an attempt is made to update the cargo object (which does not exist).

I guess what you actually want is cargo object to be created first and then the item object to be created with the id of the cargo object as the reference - so, essentally re-look at the save() method in the Action class.

What is the best way to conditionally apply a class?

Ternary operator has just been added to angular parser in 1.1.5.

So the simplest way to do this is now :

ng:class="($index==selectedIndex)? 'selected' : ''"

Oracle: how to UPSERT (update or insert into a table?)

An alternative to MERGE (the "old fashioned way"):

begin
   insert into t (mykey, mystuff) 
      values ('X', 123);
exception
   when dup_val_on_index then
      update t 
      set    mystuff = 123 
      where  mykey = 'X';
end;   

phpmailer error "Could not instantiate mail function"

This worked for me

$mail->SetFrom("[email protected]","my name", 0); //notice the third parameter

How do I execute a stored procedure once for each row returned by query?

I like the dynamic query way of Dave Rincon as it does not use cursors and is small and easy. Thank you Dave for sharing.

But for my needs on Azure SQL and with a "distinct" in the query, i had to modify the code like this:

Declare @SQL nvarchar(max);
-- Set SQL Variable
-- Prepare exec command for each distinctive tenantid found in Machines 
SELECT @SQL = (Select distinct 'exec dbo.sp_S2_Laser_to_cache ' + 
              convert(varchar(8),tenantid) + ';' 
              from Dim_Machine
              where iscurrent = 1
              FOR XML PATH(''))

--for debugging print the sql 
print @SQL;

--execute the generated sql script
exec sp_executesql @SQL;

I hope this helps someone...

How to use JQuery with ReactJS

Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-

  1. npm install jquery --save

  2. Then, import $ from "jquery";

    See here

How to dynamically create a class?

You can also dynamically create a class by using DynamicObject.

public class DynamicClass : DynamicObject
{
    private Dictionary<string, KeyValuePair<Type, object>> _fields;

    public DynamicClass(List<Field> fields)
    {
        _fields = new Dictionary<string, KeyValuePair<Type, object>>();
        fields.ForEach(x => _fields.Add(x.FieldName,
            new KeyValuePair<Type, object>(x.FieldType, null)));
    }

    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
        if (_fields.ContainsKey(binder.Name))
        {
            var type = _fields[binder.Name].Key;
            if (value.GetType() == type)
            {
                _fields[binder.Name] = new KeyValuePair<Type, object>(type, value);
                return true;
            }
            else throw new Exception("Value " + value + " is not of type " + type.Name);
        }
        return false;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        result = _fields[binder.Name].Value;
        return true;
    }
}

I store all class fields in a dictionary _fields together with their types and values. The both methods are to can get or set value to some of the properties. You must use the dynamic keyword to create an instance of this class.

The usage with your example:

var fields = new List<Field>() { 
    new Field("EmployeeID", typeof(int)),
    new Field("EmployeeName", typeof(string)),
    new Field("Designation", typeof(string)) 
};

dynamic obj = new DynamicClass(fields);

//set
obj.EmployeeID = 123456;
obj.EmployeeName = "John";
obj.Designation = "Tech Lead";

obj.Age = 25;             //Exception: DynamicClass does not contain a definition for 'Age'
obj.EmployeeName = 666;   //Exception: Value 666 is not of type String

//get
Console.WriteLine(obj.EmployeeID);     //123456
Console.WriteLine(obj.EmployeeName);   //John
Console.WriteLine(obj.Designation);    //Tech Lead

Edit: And here is how looks my class Field:

public class Field
{
    public Field(string name, Type type)
    {
        this.FieldName = name;
        this.FieldType = type;
    }

    public string FieldName;

    public Type FieldType;
}

Print content of JavaScript object?

Simple function to alert contents of an object or an array .
Call this function with an array or string or an object it alerts the contents.

Function

function print_r(printthis, returnoutput) {
    var output = '';

    if($.isArray(printthis) || typeof(printthis) == 'object') {
        for(var i in printthis) {
            output += i + ' : ' + print_r(printthis[i], true) + '\n';
        }
    }else {
        output += printthis;
    }
    if(returnoutput && returnoutput == true) {
        return output;
    }else {
        alert(output);
    }
}

Usage

var data = [1, 2, 3, 4];
print_r(data);

How to add hours to current date in SQL Server?

Select JoiningDate ,Dateadd (day , 30 , JoiningDate)
from Emp

Select JoiningDate ,DateAdd (month , 10 , JoiningDate)
from Emp

Select JoiningDate ,DateAdd (year , 10 , JoiningDate )
from Emp

Select DateAdd(Hour, 10 , JoiningDate )
from emp


Select dateadd (hour , 10 , getdate()), getdate()

Select dateadd (hour , 10 , joiningDate)
from Emp


Select DateAdd (Second , 120 , JoiningDate ) , JoiningDate 
From EMP

git: fatal: Could not read from remote repository

In my case I was using an ssh key with a password to authenticate with github. I hadn't set up pageant properly in Windows (only in cygwin). The missing steps were to point the git_ssh environment variable to plink.exe. Also, you need to get github.com into the plink known_hosts.

   plink github.com
   y
   <then ctrl-c>

Hope this helps!

I sure wish intellij would have given me a more useful error, or better yet asked me to type in the ssh key password.

In STL maps, is it better to use map::insert than []?

If the performance hit of the default constructor isn't an issue, the please, for the love of god, go with the more readable version.

:)

Is it bad practice to use break to exit a loop in Java?

Using break in loops can be perfectly legitimate and it can even be the only way to solve some problems.

However, it's bad reputation comes from the fact that new programmers usually abuse it, leading to confusing code, especially by using break to stop the loop in conditions that could have been written in the loop condition statement in the first place.

Best Practices: working with long, multiline strings in PHP?

The one who believes that

"abc\n" . "def\n"

is multiline string is wrong. That's two strings with concatenation operator, not a multiline string. Such concatenated strings cannot be used as keys of pre-defined arrays, for example. Unfortunately php does not offer real multiline strings in form of

"abc\n"
"def\n"

only HEREDOC and NOWDOC syntax, which is more suitable for templates, because nested code indent is broken by such syntax.

How do I show the value of a #define at compile-time?

Instead of #error, try redefining the macro, just before it is being used. Compilation will fail and compiler will provide the current value it thinks applies to the macro.

#define BOOST_VERSION blah

How to simulate a click with JavaScript?

Have you considered using jQuery to avoid all the browser detection? With jQuery, it would be as simple as:

$("#mytest1").click();

VB.NET Switch Statement GoTo Case

Select Case parameter
    ' does something here.
    ' does something here.
    Case "userID", "packageID", "mvrType"
                ' does something here.
        If otherFactor Then
        Else
            goto case default
        End If
    Case Else
        ' does some processing...
        Exit Select
End Select

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

In case anyone else comes by this issue, the default port on MAMP for mysql is 8889, but the port that php expects to use for mysql is 3306. So you need to open MAMP, go to preferences, and change the MAMP mysql port to 3306, then restart the mysql server. Now the connection should be successful with host=localhost, user=root, pass=root.

Why do we need to use flatMap?

When I started to have a look at Rxjs I also stumbled on that stone. What helped me is the following:

  • documentation from reactivex.io . For instance, for flatMap: http://reactivex.io/documentation/operators/flatmap.html
  • documentation from rxmarbles : http://rxmarbles.com/. You will not find flatMap there, you must look at mergeMap instead (another name).
  • the introduction to Rx that you have been missing: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754. It addresses a very similar example. In particular it addresses the fact that a promise is akin to an observable emitting only one value.
  • finally looking at the type information from RxJava. Javascript not being typed does not help here. Basically if Observable<T> denotes an observable object which pushes values of type T, then flatMap takes a function of type T' -> Observable<T> as its argument, and returns Observable<T>. map takes a function of type T' -> T and returns Observable<T>.

    Going back to your example, you have a function which produces promises from an url string. So T' : string, and T : promise. And from what we said before promise : Observable<T''>, so T : Observable<T''>, with T'' : html. If you put that promise producing function in map, you get Observable<Observable<T''>> when what you want is Observable<T''>: you want the observable to emit the html values. flatMap is called like that because it flattens (removes an observable layer) the result from map. Depending on your background, this might be chinese to you, but everything became crystal clear to me with typing info and the drawing from here: http://reactivex.io/documentation/operators/flatmap.html.

To show error message without alert box in Java Script

Try this code

<html>
<head>
 <script type="text/javascript">
 function validate() {
  if(myform.fname.value.length==0)
  {
document.getElementById('errfn').innerHTML="this is invalid name";
  }
 }
 </script>
</head>
<body>
 <form name="myform">
  First_Name
  <input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn">   </div>

<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>

<br>
<input type=button value=check> 

</form>
</body>
</html>

How can I use Timer (formerly NSTimer) in Swift?

NSTimer has been renamed to Timer in Swift 4.2. this syntax will work in 4.2:

let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(UIMenuController.update), userInfo: nil, repeats: true)

Hiding and Showing TabPages in tabControl

There are at least two ways to code a solution in software... Thanks for posting answers. Just wanted to update this with another version. A TabPage array is used to shadow the Tab Control. During the Load event, the TabPages in the TabControl are copied to the shadow array. Later, this shadow array is used as the source to copy the TabPages into the TabControl...and in the desired presentation order.

    Private tabControl1tabPageShadow() As TabPage = Nothing

    Private Sub Form2_DailyReportPackageViewer_Load(sender As Object, e As EventArgs) Handles Me.Load
        LoadTabPageShadow()
    End Sub


    Private Sub LoadTabPageShadow()
        ReDim tabControl1tabPageShadow(TabControl1.TabPages.Count - 1)
        For Each tabPage In TabControl1.TabPages
            tabControl1tabPageShadow(tabPage.TabIndex) = tabPage
        Next
    End Sub

    Private Sub ViewAllReports(sender As Object, e As EventArgs) Handles Button8.Click
        TabControl1.TabPages.Clear()
        For Each tabPage In tabControl1tabPageShadow
            TabControl1.TabPages.Add(tabPage)
        Next
    End Sub


    Private Sub ViewOperationsReports(sender As Object, e As EventArgs) Handles Button10.Click
        TabControl1.TabPages.Clear()

        For tabCount As Integer = 0 To 9
            For Each tabPage In tabControl1tabPageShadow
                Select Case tabPage.Text
                    Case "Overview"
                        If tabCount = 0 Then TabControl1.TabPages.Add(tabPage)
                    Case "Production Days Under 110%"
                        If tabCount = 1 Then TabControl1.TabPages.Add(tabPage)
                    Case "Screening Status"
                        If tabCount = 2 Then TabControl1.TabPages.Add(tabPage)
                    Case "Rework Status"
                        If tabCount = 3 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary by Machine"
                        If tabCount = 4 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary Set Ups"
                        If tabCount = 5 Then TabControl1.TabPages.Add(tabPage)
                    Case "Secondary Run Times"
                        If tabCount = 6 Then TabControl1.TabPages.Add(tabPage)
                    Case "Primary Set Ups"
                        If tabCount = 7 Then TabControl1.TabPages.Add(tabPage)
                    Case "Variance"
                        If tabCount = 8 Then TabControl1.TabPages.Add(tabPage)
                    Case "Schedule Changes"
                        If tabCount = 9 Then TabControl1.TabPages.Add(tabPage)
                End Select
            Next
        Next


NumPy first and last element from array

arr = np.array([1,2,3,4])
arr[-1] # last element

You can't specify target table for update in FROM clause

If you are trying to read fieldA from tableA and save it on fieldB on the same table, when fieldc = fieldd you might want consider this.

UPDATE tableA,
    tableA AS tableA_1 
SET 
    tableA.fieldB= tableA_1.filedA
WHERE
    (((tableA.conditionFild) = 'condition')
        AND ((tableA.fieldc) = tableA_1.fieldd));

Above code copies the value from fieldA to fieldB when condition-field met your condition. this also works in ADO (e.g access )

source: tried myself

IF a cell contains a string

You can use OR() to group expressions (as well as AND()):

=IF(OR(condition1, condition2), true, false)

=IF(AND(condition1, condition2), true, false)

So if you wanted to test for "cat" and "22":

=IF(AND(SEARCH("cat",a1),SEARCH("22",a1)),"cat and 22","none")

How the int.TryParse actually works

We can now in C# 7.0 and above write this:

if (int.TryParse(inputString, out _))
{
    //do stuff
}

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

SQL distinct for 2 fields in a database

If you want distinct values from only two fields, plus return other fields with them, then the other fields must have some kind of aggregation on them (sum, min, max, etc.), and the two columns you want distinct must appear in the group by clause. Otherwise, it's just as Decker says.

Alter user defined type in SQL Server

We are using the following procedure, it allows us to re-create a type from scratch, which is "a start". It renames the existing type, creates the type, recompiles stored procs and then drops the old type. This takes care of scenarios where simply dropping the old type-definition fails due to references to that type.

Usage Example:

exec RECREATE_TYPE @schema='dbo', @typ_nme='typ_foo', @sql='AS TABLE([bar] varchar(10) NOT NULL)'

Code:

CREATE PROCEDURE [dbo].[RECREATE_TYPE]
    @schema     VARCHAR(100),       -- the schema name for the existing type
    @typ_nme    VARCHAR(128),       -- the type-name (without schema name)
    @sql        VARCHAR(MAX)        -- the SQL to create a type WITHOUT the "CREATE TYPE schema.typename" part
AS DECLARE
    @scid       BIGINT,
    @typ_id     BIGINT,
    @temp_nme   VARCHAR(1000),
    @msg        VARCHAR(200)
BEGIN
    -- find the existing type by schema and name
    SELECT @scid = [SCHEMA_ID] FROM sys.schemas WHERE UPPER(name) = UPPER(@schema);
    IF (@scid IS NULL) BEGIN
        SET @msg = 'Schema ''' + @schema + ''' not found.';
        RAISERROR (@msg, 1, 0);
    END;
    SELECT @typ_id = system_type_id FROM sys.types WHERE UPPER(name) = UPPER(@typ_nme);
    SET @temp_nme = @typ_nme + '_rcrt'; -- temporary name for the existing type

    -- if the type-to-be-recreated actually exists, then rename it (give it a temporary name)
    -- if it doesn't exist, then that's OK, too.
    IF (@typ_id IS NOT NULL) BEGIN
        exec sp_rename @objname=@typ_nme, @newname= @temp_nme, @objtype='USERDATATYPE'
    END;    

    -- now create the new type
    SET @sql = 'CREATE TYPE ' + @schema + '.' + @typ_nme + ' ' + @sql;
    exec sp_sqlexec @sql;

    -- if we are RE-creating a type (as opposed to just creating a brand-spanking-new type)...
    IF (@typ_id IS NOT NULL) BEGIN
        exec recompile_prog;    -- then recompile all stored procs (that may have used the type)
        exec sp_droptype @typename=@temp_nme;   -- and drop the temporary type which is now no longer referenced
    END;    
END

GO


CREATE PROCEDURE [dbo].[recompile_prog]
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @v TABLE (RecID INT IDENTITY(1,1), spname sysname)
    -- retrieve the list of stored procedures
    INSERT INTO 
        @v(spname) 
    SELECT 
        '[' + s.[name] + '].[' + items.name + ']'     
    FROM 
        (SELECT sp.name, sp.schema_id, sp.is_ms_shipped FROM sys.procedures sp UNION SELECT so.name, so.SCHEMA_ID, so.is_ms_shipped FROM sys.objects so WHERE so.type_desc LIKE '%FUNCTION%') items
        INNER JOIN sys.schemas s ON s.schema_id = items.schema_id    
        WHERE is_ms_shipped = 0;

    -- counter variables
    DECLARE @cnt INT, @Tot INT;
    SELECT @cnt = 1;
    SELECT @Tot = COUNT(*) FROM @v;
    DECLARE @spname sysname
    -- start the loop
    WHILE @Cnt <= @Tot BEGIN    
        SELECT @spname = spname        
        FROM @v        
        WHERE RecID = @Cnt;
        --PRINT 'refreshing...' + @spname    
        BEGIN TRY        -- refresh the stored procedure        
            EXEC sp_refreshsqlmodule @spname    
        END TRY    
        BEGIN CATCH        
            PRINT 'Validation failed for : ' + @spname + ', Error:' + ERROR_MESSAGE();
        END CATCH    
        SET @Cnt = @cnt + 1;
    END;

END

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

Drop a temporary table if it exists

Check for the existence by retrieving its object_id:

if object_id('tempdb..##clients_keyword') is not null
    drop table ##clients_keyword

How do I pass a unique_ptr argument to a constructor or a function?

Yes you have to if you take the unique_ptr by value in the constructor. Explicity is a nice thing. Since unique_ptr is uncopyable (private copy ctor), what you wrote should give you a compiler error.

How to check the differences between local and github before the pull

And another useful command to do this (after git fetch) is:

git log origin/master ^master

This shows the commits that are in origin/master but not in master. You can also do it in opposite when doing git pull, to check what commits will be submitted to remote.

How can I select the row with the highest ID in MySQL?

This is the only proposed method who actually selects the whole row, not only the max(id) field. It uses a subquery

SELECT * FROM permlog WHERE id = ( SELECT MAX( id ) FROM permlog )

Select N random elements from a List<T> in C#

I recently did this on my project using an idea similar to Tyler's point 1.
I was loading a bunch of questions and selecting five at random. Sorting was achieved using an IComparer.
aAll questions were loaded in the a QuestionSorter list, which was then sorted using the List's Sort function and the first k elements where selected.

    private class QuestionSorter : IComparable<QuestionSorter>
    {
        public double SortingKey
        {
            get;
            set;
        }

        public Question QuestionObject
        {
            get;
            set;
        }

        public QuestionSorter(Question q)
        {
            this.SortingKey = RandomNumberGenerator.RandomDouble;
            this.QuestionObject = q;
        }

        public int CompareTo(QuestionSorter other)
        {
            if (this.SortingKey < other.SortingKey)
            {
                return -1;
            }
            else if (this.SortingKey > other.SortingKey)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }

Usage:

    List<QuestionSorter> unsortedQuestions = new List<QuestionSorter>();

    // add the questions here

    unsortedQuestions.Sort(unsortedQuestions as IComparer<QuestionSorter>);

    // select the first k elements

Why isn't Python very good for functional programming?

Guido has a good explanation of this here. Here's the most relevant part:

I have never considered Python to be heavily influenced by functional languages, no matter what people say or think. I was much more familiar with imperative languages such as C and Algol 68 and although I had made functions first-class objects, I didn't view Python as a functional programming language. However, earlier on, it was clear that users wanted to do much more with lists and functions.

...

It is also worth noting that even though I didn't envision Python as a functional language, the introduction of closures has been useful in the development of many other advanced programming features. For example, certain aspects of new-style classes, decorators, and other modern features rely upon this capability.

Lastly, even though a number of functional programming features have been introduced over the years, Python still lacks certain features found in “real” functional programming languages. For instance, Python does not perform certain kinds of optimizations (e.g., tail recursion). In general, because Python's extremely dynamic nature, it is impossible to do the kind of compile-time optimization known from functional languages like Haskell or ML. And that's fine.

I pull two things out of this:

  1. The language's creator doesn't really consider Python to be a functional language. Therefore, it's possible to see "functional-esque" features, but you're unlikely to see anything that is definitively functional.
  2. Python's dynamic nature inhibits some of the optimizations you see in other functional languages. Granted, Lisp is just as dynamic (if not more dynamic) as Python, so this is only a partial explanation.

Check if string begins with something?

A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

jquery to loop through table rows and cells, where checkob is checked, concatenate

UPDATED

I've updated your demo: http://jsfiddle.net/terryyounghk/QS56z/18/

Also, I've changed two ^= to *=. See http://api.jquery.com/category/selectors/

And note the :checked selector. See http://api.jquery.com/checked-selector/

function createcodes() {

    //run through each row
    $('.authors-list tr').each(function (i, row) {

        // reference all the stuff you need first
        var $row = $(row),
            $family = $row.find('input[name*="family"]'),
            $grade = $row.find('input[name*="grade"]'),
            $checkedBoxes = $row.find('input:checked');

        $checkedBoxes.each(function (i, checkbox) {
            // assuming you layout the elements this way, 
            // we'll take advantage of .next()
            var $checkbox = $(checkbox),
                $line = $checkbox.next(),
                $size = $line.next();

            $line.val(
                $family.val() + ' ' + $size.val() + ', ' + $grade.val()
            );

        });

    });
}

JSON find in JavaScript

General Solution

We use object-scan for a lot of data processing. It has some nice properties, especially traversing in delete safe order. Here is how one could implement find, delete and replace for your question.

_x000D_
_x000D_
// const objectScan = require('object-scan');

const tool = (() => {
  const scanner = objectScan(['[*]'], {
    abort: true,
    rtn: 'bool',
    filterFn: ({
      value, parent, property, context
    }) => {
      if (value.id === context.id) {
        context.fn({ value, parent, property });
        return true;
      }
      return false;
    }
  });
  return {
    add: (data, id, obj) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property + 1, 0, obj) }),
    del: (data, id) => scanner(data, { id, fn: ({ parent, property }) => parent.splice(property, 1) }),
    mod: (data, id, prop, v = undefined) => scanner(data, {
      id,
      fn: ({ value }) => {
        if (value !== undefined) {
          value[prop] = v;
        } else {
          delete value[prop];
        }
      }
    })
  };
})();

// -------------------------------

const data = [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ];
const toAdd = { id: 'two', pId: 'foo2', cId: 'bar2' };

const exec = (fn) => {
  console.log('---------------');
  console.log(fn.toString());
  console.log(fn());
  console.log(data);
};

exec(() => tool.add(data, 'one', toAdd));
exec(() => tool.mod(data, 'one', 'pId', 'zzz'));
exec(() => tool.mod(data, 'one', 'other', 'test'));
exec(() => tool.mod(data, 'one', 'gone', 'delete me'));
exec(() => tool.mod(data, 'one', 'gone'));
exec(() => tool.del(data, 'three'));

// => ---------------
// => () => tool.add(data, 'one', toAdd)
// => true
// => [ { id: 'one', pId: 'foo1', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'pId', 'zzz')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'other', 'test')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone', 'delete me')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: 'delete me' }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.mod(data, 'one', 'gone')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' }, { id: 'three', pId: 'foo3', cId: 'bar3' } ]
// => ---------------
// => () => tool.del(data, 'three')
// => true
// => [ { id: 'one', pId: 'zzz', cId: 'bar1', other: 'test', gone: undefined }, { id: 'two', pId: 'foo2', cId: 'bar2' } ]
_x000D_
.as-console-wrapper {max-height: 100% !important; top: 0}
_x000D_
<script src="https://bundle.run/[email protected]"></script>
_x000D_
_x000D_
_x000D_

Disclaimer: I'm the author of object-scan

How to use confirm using sweet alert?

I have been having this issue with SweetAlert2 as well. SA2 differs from 1 and puts everything inside the result object. The following above can be accomplished with the following code.

Swal.fire({
    title: 'A cool title',
    icon: 'info',
    confirmButtonText: 'Log in'
  }).then((result) => {
    if (result['isConfirmed']){
      // Put your function here
    }
  })

Everything placed inside the then result will run. Result holds a couple of parameters which can be used to do the trick. Pretty simple technique. Not sure if it works the same on SweetAlert1 but I really wouldn't know why you would choose that one above the newer version.

Not connecting to SQL Server over VPN

When this happens to me, it is because DNS is not working properly. Try using the IP address instead of the server name in the SQL Server login.

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

Class extending more than one class Java?

java can not support multiple inheritence.but u can do this in this way

class X
{
}
class Y extends X
{
}
class Z extends Y{
}

Migration: Cannot add foreign key constraint

I had this issue with laravel 5.8 and i fixed this code, as shown here in Laravel documentation, to where ever i am adding a foreign key.

$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

then i ran $ php artisan migrate:refresh

Since this syntax is rather verbose, Laravel provides additional, terser methods that use convention to provide a better developer experience. The example above could be written like so:

Schema::table('posts', function (Blueprint $table) {
    $table->foreignId('user_id')->constrained()->onDelete('cascade');
});

How to check if a socket is connected/disconnected in C#?

The best way is simply to have your client send a PING every X seconds, and for the server to assume it is disconnected after not having received one for a while.

I encountered the same issue as you when using sockets, and this was the only way I could do it. The socket.connected property was never correct.

In the end though, I switched to using WCF because it was far more reliable than sockets.

What's the best way to convert a number to a string in JavaScript?

Method toFixed() will also solves the purpose.

var n = 8.434332;
n.toFixed(2)  // 8.43

.substring error: "is not a function"

you can also quote string

''+document.location+''.substring(2,3);

Calculating sum of repeated elements in AngularJS ng-repeat

I expanded a bit on RajaShilpa's answer. You can use syntax like:

{{object | sumOfTwoValues:'quantity':'products.productWeight'}}

so that you can access an object's child object. Here is the code for the filter:

.filter('sumOfTwoValues', function () {
    return function (data, key1, key2) {
        if (typeof (data) === 'undefined' || typeof (key1) === 'undefined' || typeof (key2) === 'undefined') {
            return 0;
        }
        var keyObjects1 = key1.split('.');
        var keyObjects2 = key2.split('.');
        var sum = 0;
        for (i = 0; i < data.length; i++) {
            var value1 = data[i];
            var value2 = data[i];
            for (j = 0; j < keyObjects1.length; j++) {
                value1 = value1[keyObjects1[j]];
            }
            for (k = 0; k < keyObjects2.length; k++) {
                value2 = value2[keyObjects2[k]];
            }
            sum = sum + (value1 * value2);
        }
        return sum;
    }
});

How to determine previous page URL in Angular?

This worked for me in angular >= 6.x versions:

this.router.events
            .subscribe((event) => {
              if (event instanceof NavigationStart) {
                window.localStorage.setItem('previousUrl', this.router.url);
              }
            });

Parse String date in (yyyy-MM-dd) format

I convert String to Date in format ("yyyy-MM-dd") to save into Mysql data base .

 String date ="2016-05-01";
 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
 Date parsed = format.parse(date);
 java.sql.Date sql = new java.sql.Date(parsed.getTime());

sql it's my output in date format

MySQL Daemon Failed to Start - centos 6

I just had this error. I could not connect remotely to my mysql server. I tried restarting mysql server with service mysqld restart (I used root). It stopped but did not start again. Turns out my memory was full. Cleared out a few GBs and it is working fine.

Downgrade npm to an older version

Just replace @latest with the version number you want to downgrade to. I wanted to downgrade to version 3.10.10, so I used this command:

npm install -g [email protected]

If you're not sure which version you should use, look at the version history. For example, you can see that 3.10.10 is the latest version of npm 3.

Certificate is trusted by PC but not by Android

Make sure you also use your intermediate crt (.crt file with a bundle.. some providers also call it bundle or ca certificate). then in your ssl.conf,

SSLCertificateFile </path/for/actual/certificate>

SSLCACertificateFile </path/for/actual/intermediate_certificate>

then restart your webserver :ex for apache use :

sudo service httpd restart

JavaScript editor within Eclipse

Didn't use eclipse for a while, but there are ATF and Aptana.

Mongoose: Get full list of users

To make function to wait for list to be fetched.

getArrayOfData() {
    return DataModel.find({}).then(function (storedDataArray) {
        return storedDataArray;
    }).catch(function(err){
        if (err) {
            throw new Error(err.message);
        }
    });
}

Find text string using jQuery?

If you just want the node closest to the text you're searching for, you could use this:

$('*:contains("my text"):last');

This will even work if your HTML looks like this:

<p> blah blah <strong>my <em>text</em></strong></p>

Using the above selector will find the <strong> tag, since that's the last tag which contains that entire string.

merge two object arrays with Angular 2 and TypeScript?

You can also use the form recommended by ES6:

data => {
  this.results = [
    ...this.results,
    data.results,
  ];
  this._next = data.next;
},

This works if you initialize your array first (public results = [];); otherwise replace ...this.results, by ...this.results ? this.results : [],.

Hope this helps

CSS list item width/height does not work

Using width/height on inline elements is not always a good idea. You can use display: inline-block instead

Can I have an IF block in DOS batch file?

Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.

I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:

for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

How to enable support of CPU virtualization on Macbook Pro?

Here is a way to check is virtualization is enabled or disabled by the firmware as suggested by this link in parallels.com.

How to check that Intel VT-x is supported in CPU:

  1. Open Terminal application from Application/Utilities

  2. Copy/paste command bellow

sysctl -a | grep machdep.cpu.features

  1. You may see output similar to:

Mac:~ user$ sysctl -a | grep machdep.cpu.features kern.exec: unknown type returned machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM SSE3 MON VMX EST TM2 TPR PDCM

If you see VMX entry then CPU supports Intel VT-x feature, but it still may be disabled.

Refer to this link on Apple.com to enable hardware support for virtualization:

Edit Crystal report file without Crystal Report software

I wouldn't have thought so.

If you have Visual Studio you could edit them through that. Some versions of Visual Studio has Crystal Reports shipped with them.

If not, you will have to find someone who has Crystal Reports and ask then nicely to amend them for you. Or buy Crystal Reports!