Programs & Examples On #Unfold

Docker-compose: node_modules not present in a volume after npm install succeeds

If you don't use docker-compose you can do it like this:

FROM node:10

WORKDIR /usr/src/app

RUN npm install -g @angular/cli

COPY package.json ./
RUN npm install

EXPOSE 5000

CMD ng serve --port 5000 --host 0.0.0.0

Then you build it: docker build -t myname . and you run it by adding two volumes, the second one without source: docker run --rm -it -p 5000:5000 -v "$PWD":/usr/src/app/ -v /usr/src/app/node_modules myname

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

How to git ignore subfolders / subdirectories?

To exclude content and subdirectories:

**/bin/*

To just exclude all subdirectories but take the content, add "/":

**/bin/*/

Calculating the sum of two variables in a batch script

@ECHO OFF
TITLE Addition
ECHO Type the first number you wish to add:
SET /P Num1Add=
ECHO Type the second number you want to add to the first number:
SET /P Num2Add=
ECHO.
SET /A Ans=%Num1Add%+%Num2Add%
ECHO The result is: %Ans%
ECHO.
ECHO Press any key to exit.
PAUSE>NUL

Reading serial data in realtime in Python

You can use inWaiting() to get the amount of bytes available at the input queue.

Then you can use read() to read the bytes, something like that:

While True:
    bytesToRead = ser.inWaiting()
    ser.read(bytesToRead)

Why not to use readline() at this case from Docs:

Read a line which is terminated with end-of-line (eol) character (\n by default) or until timeout.

You are waiting for the timeout at each reading since it waits for eol. the serial input Q remains the same it just a lot of time to get to the "end" of the buffer, To understand it better: you are writing to the input Q like a race car, and reading like an old car :)

iterating through Enumeration of hastable keys throws NoSuchElementException error

Every time you call e.nextElement() you take the next object from the iterator. You have to check e.hasMoreElement() between each call.


Example:

while(e.hasMoreElements()){
    String param = e.nextElement();
    System.out.println(param);
}

How to print VARCHAR(MAX) using Print Statement?

Uses Line Feeds and spaces as a good break point:

declare @sqlAll as nvarchar(max)
set @sqlAll = '-- Insert all your sql here'

print '@sqlAll - truncated over 4000'
print @sqlAll
print '   '
print '   '
print '   '

print '@sqlAll - split into chunks'
declare @i int = 1, @nextspace int = 0, @newline nchar(2)
set @newline = nchar(13) + nchar(10)


while Exists(Select(Substring(@sqlAll,@i,3000))) and (@i < LEN(@sqlAll))
begin
    while Substring(@sqlAll,@i+3000+@nextspace,1) <> ' ' and Substring(@sqlAll,@i+3000+@nextspace,1) <> @newline
    BEGIN
        set @nextspace = @nextspace + 1
    end
    print Substring(@sqlAll,@i,3000+@nextspace)
    set @i = @i+3000+@nextspace
    set @nextspace = 0
end
print '   '
print '   '
print '   '

How to convert a string from uppercase to lowercase in Bash?

Why not execute in backticks ?

 x=`echo "$y" | tr '[:upper:]' '[:lower:]'` 

This assigns the result of the command in backticks to the variable x. (i.e. it's not particular to tr but is a common pattern/solution for shell scripting)

You can use $(..) instead of the backticks. See here for more info.

Find empty or NaN entry in Pandas Dataframe

I've resorted to

df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index

lately. That gets both null and empty-string cells in one go.

Java abstract interface

It's not necessary, as interfaces are by default abstract as all the methods in an interface are abstract.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd/mm/yy format.

select  LEFT(convert(varchar(10), @date, 103),6) + Right(Year(@date)+ 1,2)

Convert json data to a html table

You can use simple jQuery jPut plugin

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{name}}</td>
         <td>{{email}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>

Maven dependency for Servlet 3.0 API?

Place this dependency, and dont forget to select : Include dependencies with "provided" scope

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

Ignore outliers in ggplot2 boxplot

I had the same problem and precomputed the values for Q1, Q2, median, ymin, ymax using boxplot.stats:

# Load package and generate data
library(ggplot2)
data <- rnorm(100)

# Compute boxplot statistics
stats <- boxplot.stats(data)$stats
df <- data.frame(x="label1", ymin=stats[1], lower=stats[2], middle=stats[3], 
                 upper=stats[4], ymax=stats[5])

# Create plot
p <- ggplot(df, aes(x=x, lower=lower, upper=upper, middle=middle, ymin=ymin, 
                    ymax=ymax)) + 
    geom_boxplot(stat="identity")
p

The result is a boxplot without outliers. enter image description here

How to check if variable is array?... or something array-like

Since PHP 7.1 there is a pseudo-type iterable for exactly this purpose. Type-hinting iterable accepts any array as well as any implementation of the Traversable interface. PHP 7.1 also introduced the function is_iterable(). For older versions, see other answers here for accomplishing the equivalent type enforcement without the newer built-in features.

Fair play: As BlackHole pointed out, this question appears to be a duplicate of Iterable objects and array type hinting? and his or her answer goes into further detail than mine.

Setting Oracle 11g Session Timeout

Check applications connection Pool settings, rather than altering any session timout settings on the oracle db. It's normal that they time out.

Have a look here: http://grails.org/doc/1.0.x/guide/3.%20Configuration.html#3.3%20The%20DataSource

Are you sure that you have set the "pooled" parameter correctly?

Greetings, Lars


EDIT:
Your config seems ok on first glimpse. I came across this issue today. Maybe it is related to your pain:
"Infinite loop of exceptions if the application is started when the database is down for maintenance"

What is the use of a cursor in SQL Server?

Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop). To use cursors in SQL procedures, you need to do the following: 1.Declare a cursor that defines a result set. 2.Open the cursor to establish the result set. 3.Fetch the data into local variables as needed from the cursor, one row at a time. 4.Close the cursor when done.

for ex:

declare @tab table
(
Game varchar(15),
Rollno varchar(15)
)
insert into @tab values('Cricket','R11')
insert into @tab values('VollyBall','R12')

declare @game  varchar(20)
declare @Rollno varchar(20)

declare cur2 cursor for select game,rollno from @tab 

open cur2

fetch next from cur2 into @game,@rollno

WHILE   @@FETCH_STATUS = 0   
begin

print @game

print @rollno

FETCH NEXT FROM cur2 into @game,@rollno

end

close cur2

deallocate cur2

How to convert an int to a hex string?

This will convert an integer to a 2 digit hex string with the 0x prefix:

strHex = "0x%0.2X" % 255

javascript code to check special characters

If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.

var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
    alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
    return false;
}

What does the ELIFECYCLE Node.js error mean?

One might think this is because outdated versions of npm and node, but it's not the case.

Just as Pierre Inglebert says, if you look into the source you can see that End of lifecycle means the program unexpectedly stopped. This can have various reasons. So it's not a syntax error and not an expected exception/error.

The error appeared to me when a different tool was already using the http port (3000) defined in my node scripts. When you run your node app on port 80, make sure you have stopped Apache webserver (as an example).

How to write inline if statement for print?

Try this . It might help you

a=100
b=True

if b:
   print a

How to convert any Object to String?

If the class does not have toString() method, then you can use ToStringBuilder class from org.apache.commons:commons-lang3

pom.xml:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.10</version>
</dependency>

code:

ToStringBuilder.reflectionToString(yourObject)

Java Read Large Text File With 70million line of text

I tried the following three methods, my file size is 1M, and I got results:

enter image description here

I run the program several times it looks that BufferedReader is faster.

@Test
public void testLargeFileIO_Scanner() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    InputStream inputStream = new FileInputStream(fileName);

    try (Scanner fileScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine();
            //System.out.println(line);
        }
    }
    long end = new Date().getTime();

    long time = end - start;
    System.out.println("Scanner Time Consumed => " + time);

}


@Test
 public void testLargeFileIO_BufferedReader() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    try (BufferedReader fileBufferReader = new BufferedReader(new FileReader(fileName))) {
        String fileLineContent;
        while ((fileLineContent = fileBufferReader.readLine()) != null) {
            //System.out.println(fileLineContent);
        }
    }
    long end = new Date().getTime();

    long time = (long) (end - start);
    System.out.println("BufferedReader Time Consumed => " + time);

}


@Test
public void testLargeFileIO_Stream() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    try (Stream inputStream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)) {
        //inputStream.forEach(System.out::println);
    }
    long end = new Date().getTime();

    long time = end - start;
    System.out.println("Stream Time Consumed => " + time);

}

How to save all files from source code of a web site?

In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as

save page as  
filename     : any_name.html 
save as type : webpage complete.

Then you will get any_name.html and any_name folder.

how to convert string into time format and add two hours

//the parsed time zone offset:
DateTimeFormatter dateFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String fromDateTimeObj = "2011-01-03T12:00:00.000-0800";
DateTime fromDatetime = dateFormat.withOffsetParsed().parseDateTime(fromDateTimeObj);

Find Oracle JDBC driver in Maven repository

As of today (27, February 2020) Oracle announced that it has published all JDBC client libraries from version 11.2.0.4 (e.g. ojdbc6) to 19.3.0 (e.g. ojdbc10) on Maven Central under the group id com.oracle.database:

Example:

<dependency>
  <groupId>com.oracle.database.jdbc</groupId>
  <artifactId>ojdbc10</artifactId>
  <version>19.3.0.0</version>
</dependency>

How to set MimeBodyPart ContentType to "text/html"?

Try with this:

msg.setContent(email.getBody(), "text/html; charset=ISO-8859-1");

VSCode: How to Split Editor Vertically

In version 1.23.1, it is Ctrl+Shift+P and Split Editor This will divide the screens vertically and you can move through them using Ctrl+K+LeftArrow

Screenshot of the Split Editor

Search a text file and print related lines in Python?

searchfile = open("file.txt", "r")
for line in searchfile:
    if "searchphrase" in line: print line
searchfile.close()

To print out multiple lines (in a simple way)

f = open("file.txt", "r")
searchlines = f.readlines()
f.close()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

The comma in print l, prevents extra spaces from appearing in the output; the trailing print statement demarcates results from different lines.

Or better yet (stealing back from Mark Ransom):

with open("file.txt", "r") as f:
    searchlines = f.readlines()
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        for l in searchlines[i:i+3]: print l,
        print

how to create a Java Date object of midnight today and midnight tomorrow?

Because of one day is 24 * 60 * 60 * 1000 ms, the midnight of this day can be calculate as...

long now = System.currentTimeMillis();
long delta = now % 24 * 60 * 60 * 1000;
long midnight = now - delta;
Date midnightDate = new Date(midnight);`

Font size of TextView in Android application changes on changing font size from native settings

simple way to prevent the whole app from getting effected by system font size is to updateConfiguration using a base activity.

//in base activity add this code.
public  void adjustFontScale( Configuration configuration) {

    configuration.fontScale = (float) 1.0;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);

}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    adjustFontScale( getResources().getConfiguration());
}

Marquee text in Android

I found a Problem with marquee that it can't be used for short strings(As its function is only to Show Long strings).

I suggest Use Webview If you want to move short strings horizontally. Main_Activity.java Code:`

        WebView webView;

        webView = (WebView)findViewById(R.id.web);


        String summary = "<html><FONT color='#fdb728' FACE='courier'><marquee behavior='scroll' direction='left' scrollamount=10>"
                + "Hello Droid" + "</marquee></FONT></html>";

        webView.loadData(summary, "text/html", "utf-8"); // Set focus to the textview
`

main_activity.xml code:

<WebView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/web"
        ></WebView>

How do I convert a byte array to Base64 in Java?

Additionally, for our Android friends (API Level 8):

import android.util.Base64

...

Base64.encodeToString(bytes, Base64.DEFAULT);

What is the behavior difference between return-path, reply-to and from?

Let's start with a simple example. Let's say you have an email list, that is going to send out the following RFC2822 content.

From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.

Now, let's say you are going to send it from a mailing list, that implements VERP (or some other bounce tracking mechanism that uses a different return-path). Lets say it will have a return-path of [email protected]. The SMTP session might look like:

{S}220 workstation1 Microsoft ESMTP MAIL Service
{C}HELO workstation1
{S}250 workstation1 Hello [127.0.0.1]
{C}MAIL FROM:<[email protected]>
{S}250 2.1.0 [email protected] OK
{C}RCPT TO:<[email protected]>
{S}250 2.1.5 [email protected] 
{C}DATA
{S}354 Start mail input; end with <CRLF>.<CRLF>
{C}From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.
.

{S}250 Queued mail for delivery
{C}QUIT
{S}221 Service closing transmission channel

Where {C} and {S} represent Client and Server commands, respectively.

The recipient's mail would look like:

Return-Path: [email protected]
From: <[email protected]>
To: <[email protected]>
Subject: Super simple email
Reply-To: <[email protected]>

This is a very simple body.

Now, let's describe the different "FROM"s.

  1. The return path (sometimes called the reverse path, envelope sender, or envelope from — all of these terms can be used interchangeably) is the value used in the SMTP session in the MAIL FROM command. As you can see, this does not need to be the same value that is found in the message headers. Only the recipient's mail server is supposed to add a Return-Path header to the top of the email. This records the actual Return-Path sender during the SMTP session. If a Return-Path header already exists in the message, then that header is removed and replaced by the recipient's mail server.

All bounces that occur during the SMTP session should go back to the Return-Path address. Some servers may accept all email, and then queue it locally, until it has a free thread to deliver it to the recipient's mailbox. If the recipient doesn't exist, it should bounce it back to the recorded Return-Path value.

Note, not all mail servers obey this rule; Some mail servers will bounce it back to the FROM address.

  1. The FROM address is the value found in the FROM header. This is supposed to be who the message is FROM. This is what you see as the "FROM" in most mail clients. If an email does not have a Reply-To header, then all human (mail client) replies should go back to the FROM address.

  2. The Reply-To header is added by the sender (or the sender's software). It is where all human replies should be addressed too. Basically, when the user clicks "reply", the Reply-To value should be the value used as the recipient of the newly composed email. The Reply-To value should not be used by any server. It is meant for client-side (MUA) use only.

However, as you can tell, not all mail servers obey the RFC standards or recommendations.

Hopefully this should help clear things up. However, if I missed anything, let me know, and I'll try to answer.

DropDownList in MVC 4 with Razor

Here is the easiest answer:

in your view only just add:

@Html.DropDownListFor(model => model.tipo, new SelectList(new[]{"Exemplo1",
"Exemplo2", "Exemplo3"}))

OR in your controller add:

var exemploList= new SelectList(new[] { "Exemplo1:", "Exemplo2", "Exemplo3" });
        ViewBag.ExemploList = exemploList;

and your view just add:

@Html.DropDownListFor(model => model.tipo, (SelectList)ViewBag.ExemploList )

I learned this with Jess Chadwick

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Angular 2 How to redirect to 404 or other path if the path does not exist

As Angular moved on with the release, I faced this same issue. As per version 2.1.0 the Route interface looks like:

export interface Route {
    path?: string;
    pathMatch?: string;
    component?: Type<any>;
    redirectTo?: string;
    outlet?: string;
    canActivate?: any[];
    canActivateChild?: any[];
    canDeactivate?: any[];
    canLoad?: any[];
    data?: Data;
    resolve?: ResolveData;
    children?: Route[];
    loadChildren?: LoadChildren;
} 

So my solutions was the following:

const routes: Routes = [
    { path: '', component: HomeComponent },
    { path: '404', component: NotFoundComponent },
    { path: '**', redirectTo: '404' }
];

How to access model hasMany Relation with where condition?

I have fixed the similar issue by passing associative array as the first argument inside Builder::with method.

Imagine you want to include child relations by some dynamic parameters but don't want to filter parent results.

Model.php

public function child ()
{
    return $this->hasMany(ChildModel::class);
}

Then, in other place, when your logic is placed you can do something like filtering relation by HasMany class. For example (very similar to my case):

$search = 'Some search string';
$result = Model::query()->with(
    [
        'child' => function (HasMany $query) use ($search) {
            $query->where('name', 'like', "%{$search}%");
        }
    ]
);

Then you will filter all the child results but parent models will not filter. Thank you for attention.

Putting GridView data in a DataTable

user this full solution to convert gridview to datatable

 public DataTable gridviewToDataTable(GridView gv)
        {

            DataTable dtCalculate = new DataTable("TableCalculator");

            // Create Column 1: Date
            DataColumn dateColumn = new DataColumn();
            dateColumn.DataType = Type.GetType("System.DateTime");
            dateColumn.ColumnName = "date";

            // Create Column 3: TotalSales
            DataColumn loanBalanceColumn = new DataColumn();
            loanBalanceColumn.DataType = Type.GetType("System.Double");
            loanBalanceColumn.ColumnName = "loanbalance";


            DataColumn offsetBalanceColumn = new DataColumn();
            offsetBalanceColumn.DataType = Type.GetType("System.Double");
            offsetBalanceColumn.ColumnName = "offsetbalance";


            DataColumn netloanColumn = new DataColumn();
            netloanColumn.DataType = Type.GetType("System.Double");
            netloanColumn.ColumnName = "netloan";


            DataColumn interestratecolumn = new DataColumn();
            interestratecolumn.DataType = Type.GetType("System.Double");
            interestratecolumn.ColumnName = "interestrate";

            DataColumn interestrateperdaycolumn = new DataColumn();
            interestrateperdaycolumn.DataType = Type.GetType("System.Double");
            interestrateperdaycolumn.ColumnName = "interestrateperday";

            // Add the columns to the ProductSalesData DataTable
            dtCalculate.Columns.Add(dateColumn);
            dtCalculate.Columns.Add(loanBalanceColumn);
            dtCalculate.Columns.Add(offsetBalanceColumn);
            dtCalculate.Columns.Add(netloanColumn);
            dtCalculate.Columns.Add(interestratecolumn);
            dtCalculate.Columns.Add(interestrateperdaycolumn);

            foreach (GridViewRow row in gv.Rows)
            {
                DataRow dr;
                dr = dtCalculate.NewRow();

                dr["date"] = DateTime.Parse(row.Cells[0].Text);
                dr["loanbalance"] = double.Parse(row.Cells[1].Text);
                dr["offsetbalance"] = double.Parse(row.Cells[2].Text);
                dr["netloan"] = double.Parse(row.Cells[3].Text);
                dr["interestrate"] = double.Parse(row.Cells[4].Text);
                dr["interestrateperday"] = double.Parse(row.Cells[5].Text);


                dtCalculate.Rows.Add(dr);
            }



            return dtCalculate;
        }

Java error: Only a type can be imported. XYZ resolves to a package

Without further details, it sounds like an error in the import declaration of a class. Check, if all import declarations either import all classes from a package or a single class:

import all.classes.from.package.*;
import only.one.type.named.MyClass;

Edit

OK, after the edit, looks like it's a jsp problem.

Edit 2

Here is another forum entry, the problem seems to have similarities and the victim solved it by reinstalling eclipse. I'd try that one first - installing a second instance of eclipse with only the most necessary plugins, a new workspace, the project imported into that clean workspace, and hope for the best...

Send XML data to webservice using php curl

After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code:

//Store your XML Request in a variable
    $input_xml = '<AvailRequest>
            <Trip>ONE</Trip>
            <Origin>BOM</Origin>
            <Destination>JFK</Destination>
            <DepartDate>2013-09-15</DepartDate>
            <ReturnDate>2013-09-16</ReturnDate>
            <AdultPax>1</AdultPax>
            <ChildPax>0</ChildPax>
            <InfantPax>0</InfantPax>
            <Currency>INR</Currency>
            <PreferredClass>E</PreferredClass>
            <Eticket>true</Eticket>
            <Clientid>777ClientID</Clientid>
            <Clientpassword>*Your API Password</Clientpassword>
            <Clienttype>ArzooINTLWS1.0</Clienttype>
            <PreferredAirline></PreferredAirline>
    </AvailRequest>';

Now I've made a little changes in the above curl_setopt declaration as follows:

    $url = "http://59.162.33.102:9301/Avalability";

        //setting the curl parameters.
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
// Following line is compulsary to add as it is:
        curl_setopt($ch, CURLOPT_POSTFIELDS,
                    "xmlRequest=" . $input_xml);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300);
        $data = curl_exec($ch);
        curl_close($ch);

        //convert the XML result into array
        $array_data = json_decode(json_encode(simplexml_load_string($data)), true);

        print_r('<pre>');
        print_r($array_data);
        print_r('</pre>');

That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.

Arithmetic operation resulted in an overflow. (Adding integers)

The maximum value of an integer (which is signed) is 2147483647. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.

If that exception wouldn't be thrown, you'd have a value of -2145629296 for your Volume, which is most probably not wanted.

Solution: Use an Int64 for your volume. With a max value of 9223372036854775807, you're probably more on the safe side.

Create a list with initial capacity in Python

def doAppend( size=10000 ):
    result = []
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result.append(message)
    return result

def doAllocate( size=10000 ):
    result=size*[None]
    for i in range(size):
        message= "some unique object %d" % ( i, )
        result[i]= message
    return result

Results. (evaluate each function 144 times and average the duration)

simple append 0.0102
pre-allocate  0.0098

Conclusion. It barely matters.

Premature optimization is the root of all evil.

Merging cells in Excel using Apache POI

You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);

example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).

for detail refer BusyDeveloper's Guide

Missing visible-** and hidden-** in Bootstrap v4

The user Klaro suggested to restore the old visibility classes, which is a good idea. Unfortunately, their solution did not work in my project.

I think that it is a better idea to restore the old mixin of bootstrap, because it is covering all breakpoints which can be individually defined by the user.

Here is the code:

// Restore Bootstrap 3 "hidden" utility classes.
@each $bp in map-keys($grid-breakpoints) {
  .hidden-#{$bp}-up {
    @include media-breakpoint-up($bp) {
      display: none !important;
    }
  }
  .hidden-#{$bp}-down {
    @include media-breakpoint-down($bp) {
      display: none !important;
    }
  }
  .hidden-#{$bp}-only{
    @include media-breakpoint-only($bp){
      display:none !important;
    }
  }
}

In my case, I have inserted this part in a _custom.scss file which is included at this point in the bootstrap.scss:

/*!
 * Bootstrap v4.0.0-beta (https://getbootstrap.com)
 * Copyright 2011-2017 The Bootstrap Authors
 * Copyright 2011-2017 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */

@import "functions";
@import "variables";
@import "mixins";
@import "custom"; // <-- my custom file for overwriting default vars and adding the snippet from above
@import "print";
@import "reboot";
[..]

Using Pipes within ngModel on INPUT Elements in Angular

<input [ngModel]="item.value | useMyPipeToFormatThatValue" 
      (ngModelChange)="item.value=$event" name="inputField" type="text" />

The solution here is to split the binding into a one-way binding and an event binding - which the syntax [(ngModel)] actually encompasses. [] is one-way binding syntax and () is event binding syntax. When used together - [()] Angular recognizes this as shorthand and wires up a two-way binding in the form of a one-way binding and an event binding to a component object value.

The reason you cannot use [()] with a pipe is that pipes work only with one-way bindings. Therefore you must split out the pipe to only operate on the one-way binding and handle the event separately.

See Angular Template Syntax for more info.

Oracle Differences between NVL and Coalesce

Actually I cannot agree to each statement.

"COALESCE expects all arguments to be of same datatype."

This is wrong, see below. Arguments can be different data types, that is also documented: If all occurrences of expr are numeric data type or any nonnumeric data type that can be implicitly converted to a numeric data type, then Oracle Database determines the argument with the highest numeric precedence, implicitly converts the remaining arguments to that data type, and returns that data type.. Actually this is even in contradiction to common expression "COALESCE stops at first occurrence of a non-Null value", otherwise test case No. 4 should not raise an error.

Also according to test case No. 5 COALESCE does an implicit conversion of arguments.

DECLARE
    int_val INTEGER := 1;
    string_val VARCHAR2(10) := 'foo';
BEGIN

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '1. NVL(int_val,string_val) -> '|| NVL(int_val,string_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('1. NVL(int_val,string_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '2. NVL(string_val, int_val) -> '|| NVL(string_val, int_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('2. NVL(string_val, int_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '3. COALESCE(int_val,string_val) -> '|| COALESCE(int_val,string_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('3. COALESCE(int_val,string_val) -> '||SQLERRM ); 
    END;

    BEGIN
    DBMS_OUTPUT.PUT_LINE( '4. COALESCE(string_val, int_val) -> '|| COALESCE(string_val, int_val) );
    EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('4. COALESCE(string_val, int_val) -> '||SQLERRM ); 
    END;

    DBMS_OUTPUT.PUT_LINE( '5. COALESCE(SYSDATE,SYSTIMESTAMP) -> '|| COALESCE(SYSDATE,SYSTIMESTAMP) );

END;
Output:

1. NVL(int_val,string_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
2. NVL(string_val, int_val) -> foo
3. COALESCE(int_val,string_val) -> 1
4. COALESCE(string_val, int_val) -> ORA-06502: PL/SQL: numeric or value error: character to number conversion error
5. COALESCE(SYSDATE,SYSTIMESTAMP) -> 2016-11-30 09:55:55.000000 +1:0 --> This is a TIMESTAMP value, not a DATE value!

HTML table headers always visible at top of window when viewing a large table

Check out jQuery.floatThead (demos available) which is very cool, can work with DataTables too, and can even work inside an overflow: auto container.

How to format Joda-Time DateTime to only mm/dd/yyyy?

I am adding this here even though the other answers are completely acceptable. JodaTime has parsers pre built in DateTimeFormat:

dateTime.toString(DateTimeFormat.longDate());

This is most of the options printed out with their format:

shortDate:         11/3/16
shortDateTime:     11/3/16 4:25 AM
mediumDate:        Nov 3, 2016
mediumDateTime:    Nov 3, 2016 4:25:35 AM
longDate:          November 3, 2016
longDateTime:      November 3, 2016 4:25:35 AM MDT
fullDate:          Thursday, November 3, 2016
fullDateTime:      Thursday, November 3, 2016 4:25:35 AM Mountain Daylight Time

Python safe method to get value of nested dictionary

for a second level key retrieving, you can do this:

key2_value = (example_dict.get('key1') or {}).get('key2')

Capitalize only first character of string and leave others alone? (Rails)

An object oriented solution:

class String
  def capitalize_first_char
    self.sub(/^(.)/) { $1.capitalize }
  end
end

Then you can just do this:

"i'm from New York".capitalize_first_char

Laravel check if collection is empty

This is the fastest way:

if ($coll->isEmpty()) {...}

Other solutions like count do a bit more than you need which costs slightly more time.

Plus, the isEmpty() name quite precisely describes what you want to check there so your code will be more readable.

"Insufficient Storage Available" even there is lot of free space in device memory

If you have root, delete all of the folders on the path:

/data/app-lib/

And then restart your device.

I had this issue many times, and this fix worked for me each time. It even has an XDA thread.

I write all folders, because if there is a problem with one app, there is a good chance you have this issue with other apps too. Plus, it's annoying to find just the folders of the problematic app/s .

Move branch pointer to different commit without checkout

In gitk --all:

  • right click on the commit you want
  • -> create new branch
  • enter the name of an existing branch
  • press return on the dialog that confirms replacing the old branch of that name.

Beware that re-creating instead of modifying the existing branch will lose tracking-branch information. (This is generally not a problem for simple use-cases where there's only one remote and your local branch has the same name as the corresponding branch in the remote. See comments for more details, thanks @mbdevpl for pointing out this downside.)

It would be cool if gitk had a feature where the dialog box had 3 options: overwrite, modify existing, or cancel.


Even if you're normally a command-line junkie like myself, git gui and gitk are quite nicely designed for the subset of git usage they allow. I highly recommend using them for what they're good at (i.e. selectively staging hunks into/out of the index in git gui, and also just committing. (ctrl-s to add a signed-off: line, ctrl-enter to commit.)

gitk is great for keeping track of a few branches while you sort out your changes into a nice patch series to submit upstream, or anything else where you need to keep track of what you're in the middle of with multiple branches.

I don't even have a graphical file browser open, but I love gitk/git gui.

SQL Developer with JDK (64 bit) cannot find JVM

Installing jdk1.8.0_211 and setting the below variable in product.conf (located in C:\Users\\AppData\Roaming\sqldeveloper\19.1.0) to JDK8 home worked for me

SetJavaHome D:\jdk1.8.0_211

change PATH permanently on Ubuntu

Add the following line in your .profile file in your home directory (using vi ~/.profile):

PATH=$PATH:/home/me/play
export PATH

Then, for the change to take effect, simply type in your terminal:

$ . ~/.profile

How to create a WPF Window without a border that can be resized via a grip only?

If you set the AllowsTransparency property on the Window (even without setting any transparency values) the border disappears and you can only resize via the grip.

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="640" Height="480" 
    WindowStyle="None"
    AllowsTransparency="True"
    ResizeMode="CanResizeWithGrip">

    <!-- Content -->

</Window>

Result looks like:

How to read .pem file to get private and public key

If a PEM contains only one RSA private key without encryption, it must be an ASN.1 sequence structure including 9 numbers to present a Chinese Remainder Theorem (CRT) key:

  1. version (always 0)
  2. modulus (n)
  3. public exponent (e, always 65537)
  4. private exponent (d)
  5. prime p
  6. prime q
  7. d mod (p - 1) (dp)
  8. d mod (q - 1) (dq)
  9. q^-1 mod p (qinv)

We can implement an RSAPrivateCrtKey:

class RSAPrivateCrtKeyImpl implements RSAPrivateCrtKey {
    private static final long serialVersionUID = 1L;

    BigInteger n, e, d, p, q, dp, dq, qinv;

    @Override
    public BigInteger getModulus() {
        return n;
    }

    @Override
    public BigInteger getPublicExponent() {
        return e;
    }

    @Override
    public BigInteger getPrivateExponent() {
        return d;
    }

    @Override
    public BigInteger getPrimeP() {
        return p;
    }

    @Override
    public BigInteger getPrimeQ() {
        return q;
    }

    @Override
    public BigInteger getPrimeExponentP() {
        return dp;
    }

    @Override
    public BigInteger getPrimeExponentQ() {
        return dq;
    }

    @Override
    public BigInteger getCrtCoefficient() {
        return qinv;
    }

    @Override
    public String getAlgorithm() {
        return "RSA";
    }

    @Override
    public String getFormat() {
        throw new UnsupportedOperationException();
    }

    @Override
    public byte[] getEncoded() {
        throw new UnsupportedOperationException();
    }
}

Then read the private key from a PEM file:

import sun.security.util.DerInputStream;
import sun.security.util.DerValue;

static RSAPrivateCrtKey getRSAPrivateKey(String keyFile) {
    RSAPrivateCrtKeyImpl prvKey = new RSAPrivateCrtKeyImpl();
    try (BufferedReader in = new BufferedReader(new FileReader(keyFile))) {
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = in.readLine()) != null) {
            // skip "-----BEGIN/END RSA PRIVATE KEY-----"
            if (!line.startsWith("--") || !line.endsWith("--")) {
                sb.append(line);
            }
        }
        DerInputStream der = new DerValue(Base64.
                getDecoder().decode(sb.toString())).getData();
        der.getBigInteger(); // 0
        prvKey.n = der.getBigInteger();
        prvKey.e = der.getBigInteger(); // 65537
        prvKey.d = der.getBigInteger();
        prvKey.p = der.getBigInteger();
        prvKey.q = der.getBigInteger();
        prvKey.dp = der.getBigInteger();
        prvKey.dq = der.getBigInteger();
        prvKey.qinv = der.getBigInteger();
    } catch (IllegalArgumentException | IOException e) {
        logger.warn(keyFile + ": " + e.getMessage());
        return null;
    }
}

Linq UNION query to select two elements

EDIT:

Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities

This works on my side :

        List<string> materialTypes = (from u in result.Users
                                      select u.LastName)
                       .Union(from u in result.Users
                               select SqlFunctions.StringConvert((double) u.UserId)).ToList();

On yours it should be like this:

    IList<String> materialTypes = ((from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select tom.Name)
                                       .Union(from tom in context.MaterialTypes
                                       where tom.IsActive == true
                                       select SqlFunctions.StringConvert((double)tom.ID))).ToList();

Thanks, i've learnt something today :)

writing a batch file that opens a chrome URL

assuming chrome is his default browser: start http://url.site.you.com/path/to/joke should open that url in his browser.

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I was getting this error due to something even simpler (you could even say trivial). I hadn't installed the pytest module. So a simple apt install python-pytest fixed it for me.

'pytest' would have been listed in setup.py as a test dependency. Make sure you install the test requirements as well.

The ternary (conditional) operator in C

Some of the other answers given are great. But I am surprised that no one mentioned that it can be used to help enforce const correctness in a compact way.

Something like this:

const int n = (x != 0) ? 10 : 20;

so basically n is a const whose initial value is dependent on a condition statement. The easiest alternative is to make n not a const, this would allow an ordinary if to initialize it. But if you want it to be const, it cannot be done with an ordinary if. The best substitute you could make would be to use a helper function like this:

int f(int x) {
    if(x != 0) { return 10; } else { return 20; }
}

const int n = f(x);

but the ternary if version is far more compact and arguably more readable.

Changing column names of a data frame

There are a couple options with dplyr::rename() and dplyr::select():

library(dplyr)

mtcars %>% 
  tibble::rownames_to_column('car_model') %>%                            # convert rowname to a column. tibble must be installed.
  select(car_model, est_mpg = mpg, horse_power = hp, everything()) %>%   # rename specific columns and reorder
  rename(weight = wt, cylinders = cyl) %>%                               # another option for renaming specific columns that keeps everything by default
  head(2)
      car_model est_mpg horse_power cylinders disp drat weight  qsec vs am gear carb
1     Mazda RX4      21         110         6  160  3.9  2.620 16.46  0  1    4    4
2 Mazda RX4 Wag      21         110         6  160  3.9  2.875 17.02  0  1    4    4

There are also three scoped variants of dplyr::rename(): dplyr::rename_all() for all column names, dplyr::rename_if() for conditionally targeting column names, and dplyr::rename_at() for select named columns. The following example replaces spaces and periods with an underscore and converts everything to lower case:

iris %>%  
  rename_all(~gsub("\\s+|\\.", "_", .)) %>% 
  rename_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

dplyr::select_all() can also be used in a similar way:

iris %>%  
  select_all(~gsub("\\s+|\\.", "_", .)) %>% 
  select_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

Are vectors passed to functions by value or by reference in C++

If I had to guess, I'd say that you're from a Java background. This is C++, and things are passed by value unless you specify otherwise using the &-operator (note that this operator is also used as the 'address-of' operator, but in a different context). This is all well documented, but I'll re-iterate anyway:

void foo(vector<int> bar); // by value
void foo(vector<int> &bar); // by reference (non-const, so modifiable inside foo)
void foo(vector<int> const &bar); // by const-reference

You can also choose to pass a pointer to a vector (void foo(vector<int> *bar)), but unless you know what you're doing and you feel that this is really is the way to go, don't do this.

Also, vectors are not the same as arrays! Internally, the vector keeps track of an array of which it handles the memory management for you, but so do many other STL containers. You can't pass a vector to a function expecting a pointer or array or vice versa (you can get access to (pointer to) the underlying array and use this though). Vectors are classes offering a lot of functionality through its member-functions, whereas pointers and arrays are built-in types. Also, vectors are dynamically allocated (which means that the size may be determined and changed at runtime) whereas the C-style arrays are statically allocated (its size is constant and must be known at compile-time), limiting their use.

I suggest you read some more about C++ in general (specifically array decay), and then have a look at the following program which illustrates the difference between arrays and pointers:

void foo1(int *arr) { cout << sizeof(arr) << '\n'; }
void foo2(int arr[]) { cout << sizeof(arr) << '\n'; }
void foo3(int arr[10]) { cout << sizeof(arr) << '\n'; }
void foo4(int (&arr)[10]) { cout << sizeof(arr) << '\n'; }

int main()
{
    int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    foo1(arr);
    foo2(arr);
    foo3(arr);
    foo4(arr);
}

NameError: name 'reduce' is not defined in Python

Or if you use the six library

from six.moves import reduce

What is the purpose of a self executing function in javascript?

Self invoked function in javascript:

A self-invoking expression is invoked (started) automatically, without being called. A self-invoking expression is invoked right after its created. This is basically used for avoiding naming conflict as well as for achieving encapsulation. The variables or declared objects are not accessible outside this function. For avoiding the problems of minimization(filename.min) always use self executed function.

Catch multiple exceptions at once?

With C# 7 the answer from Michael Stum can be improved while keeping the readability of a switch statement:

catch (Exception ex)
{
    switch (ex)
    {
        case FormatException _:
        case OverflowException _:
            WebId = Guid.Empty;
            break;
        default:
            throw;
    }
}

And with C# 8 as switch expression:

catch (Exception ex)
{
    WebId = ex switch
    {
        _ when ex is FormatException || ex is OverflowException => Guid.Empty,
        _ => throw ex
    };
}

How do I turn off the mysql password validation?

For references and the future, one should read the doc here https://dev.mysql.com/doc/mysql-secure-deployment-guide/5.7/en/secure-deployment-password-validation.html

Then you should edit your mysqld.cnf file, for instance :

vim /etc/mysql/mysql.conf.d/mysqld.cnf

Then, add in the [mysqld] part, the following :

plugin-load-add=validate_password.so
validate_password_policy=LOW

Basically, if you edit your default, it will looks like :

[mysqld]
#
# * Basic Settings
#
user            = mysql
pid-file        = /var/run/mysqld/mysqld.pid
socket          = /var/run/mysqld/mysqld.sock
port            = 3306
basedir         = /usr
datadir         = /var/lib/mysql
tmpdir          = /tmp
lc-messages-dir = /usr/share/mysql
skip-external-locking
plugin-load-add=validate_password.so
validate_password_policy=LOW

Then, you can restart:

systemctl restart mysql

If you forget the plugin-load-add=validate_password.so part, you will it an error at restart.

Enjoy !

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Another way to do this is described below.

First, turn on iterative calculations on under File - Options - Formulas - Enable Iterative Calculation. Then set maximum iterations to 1000.

After doing this, use the following formula.

=If(D55="","",IF(C55="",NOW(),C55))

Once anything is typed into cell D55 (for this example) then C55 populates today's date and/or time depending on the cell format. This date/time will not change again even if new data is entered into cell C55 so it shows the date/time that the data was entered originally.

This is a circular reference formula so you will get a warning about it every time you open the workbook. Regardless, the formula works and is easy to use anywhere you would like in the worksheet.

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

A simple one liner:

$("#text").val( $("#text").val().replace(".", ":") );

Locking pattern for proper use of .NET MemoryCache

To avoid the global lock, you can use SingletonCache to implement one lock per key, without exploding memory usage (the lock objects are removed when no longer referenced, and acquire/release is thread safe guaranteeing that only 1 instance is ever in use via compare and swap).

Using it looks like this:

SingletonCache<string, object> keyLocks = new SingletonCache<string, object>();

const string CacheKey = "CacheKey";
static string GetCachedData()
{
    string expensiveString =null;
    if (MemoryCache.Default.Contains(CacheKey))
    {
        return MemoryCache.Default[CacheKey] as string;
    }

    // double checked lock
    using (var lifetime = keyLocks.Acquire(url))
    {
        lock (lifetime.Value)
        {
           if (MemoryCache.Default.Contains(CacheKey))
           {
              return MemoryCache.Default[CacheKey] as string;
           }

           cacheItemPolicy cip = new CacheItemPolicy()
           {
              AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(20))
           };
           expensiveString = SomeHeavyAndExpensiveCalculation();
           MemoryCache.Default.Set(CacheKey, expensiveString, cip);
           return expensiveString;
        }
    }      
}

Code is here on GitHub: https://github.com/bitfaster/BitFaster.Caching

Install-Package BitFaster.Caching

There is also an LRU implementation that is lighter weight than MemoryCache, and has several advantages - faster concurrent reads and writes, bounded size, no background thread, internal perf counters etc. (disclaimer, I wrote it).

Passing data between different controller action methods

I prefer to use this instead of TempData

public class Home1Controller : Controller 
{
    [HttpPost]
    public ActionResult CheckBox(string date)
    {
        return RedirectToAction("ActionName", "Home2", new { Date =date });
    }
}

and another controller Action is

public class Home2Controller : Controller 
{
    [HttpPost]
    Public ActionResult ActionName(string Date)
    {
       // do whatever with Date
       return View();
    }
}

it is too late but i hope to be helpful for any one in the future

Reloading/refreshing Kendo Grid

$("#grd").data("kendoGrid").dataSource.read();

'JSON' is undefined error in JavaScript in Internet Explorer

Check for extra commas in your JSON response. If the last element of an array has a comma, this will break in IE

How to access SOAP services from iPhone

Have a look at gsoap that includes two iOS examples in the download package under ios_plugin. The tool converts WSDL to code for SOAP and XML REST.

python dictionary sorting in descending order based on values

A short example to sort dictionary is desending order for Python3.

a1 = {'a':1, 'b':13, 'd':4, 'c':2, 'e':30}
a1_sorted_keys = sorted(a1, key=a1.get, reverse=True)
for r in a1_sorted_keys:
    print(r, a1[r])

Following will be the output

e 30
b 13
d 4
c 2
a 1

Share variables between files in Node.js?

With a different opinion, I think the global variables might be the best choice if you are going to publish your code to npm, cuz you cannot be sure that all packages are using the same release of your code. So if you use a file for exporting a singleton object, it will cause issues here.

You can choose global, require.main or any other objects which are shared across files.

Otherwise, install your package as an optional dependency package can avoid this problem.

Please tell me if there are some better solutions.

PDO mysql: How to know if insert was successful

You can test the rowcount

    $sqlStatement->execute( ...);
    if ($sqlStatement->rowCount() > 0)
    {
        return true;
    }

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

How do I repair an InnoDB table?

Step 1.

Stop MySQL server

Step 2.

add this line to my.cnf ( In windows it is called my.ini )

set-variable=innodb_force_recovery=6

Step 3.

delete ib_logfile0 and ib_logfile1

Step 4.

Start MySQL server

Step 5.

Run this command:

mysqlcheck --database db_name table_name -uroot -p

After you have successfully fixed the crashed innodb table, don't forget to remove #set-variable=innodb_force_recovery=6 from my.cnf and then restart MySQL server again.

WPF C# button style

Here's my attempt. Looks more similar to the OP's sample and provides settable properties for icon (FrameworkElement), title (string) and subtitle (string). The output looks like this:

enter image description here

Here's XAML:

<Button x:Class="Controls.FancyButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Width="300" Height="80"
          BorderBrush="{x:Null}" BorderThickness="0">
  <Button.Effect>
    <DropShadowEffect BlurRadius="12" Color="Gray" Direction="270" Opacity=".8" ShadowDepth="3" />
  </Button.Effect>

  <Button.Template>
    <ControlTemplate TargetType="Button">
      <Grid Width="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualWidth}"
        Height="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualHeight}">

        <Border x:Name="MainBorder" CornerRadius="3" Grid.ColumnSpan="2" Margin="0,0,4,4" BorderBrush="Black" BorderThickness="1">
          <Border.Background>
            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
              <GradientStop Color="#FF5E5E5E" Offset="0" />
              <GradientStop Color="#FF040404" Offset="1" />
            </LinearGradientBrush>
          </Border.Background>

          <Grid >
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="1.2*"/>
              <ColumnDefinition Width="3*"/>
            </Grid.ColumnDefinitions>

            <Border CornerRadius="2" Margin="0" BorderBrush="LightGray" BorderThickness="0,1,0,0" Grid.ColumnSpan="2" Grid.RowSpan="2" />

            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="0" HorizontalAlignment="Right" Stroke="#0C0C0C" Grid.RowSpan="2" />
            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="1" HorizontalAlignment="Left" Grid.RowSpan="2">
              <Line.Stroke>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                  <GradientStop Color="#4D4D4D" Offset="0" />
                  <GradientStop Color="#2C2C2C" Offset="1" />
                </LinearGradientBrush>
              </Line.Stroke>
            </Line>

            <ContentControl HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2">
              <ContentControl.Content>
                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Image">
                  <Binding.FallbackValue>
                    <Path Data="M0,0 L30,15 L0,30Z">
                      <Path.Effect>
                        <DropShadowEffect Direction="50" ShadowDepth="2" />
                      </Path.Effect>
                      <Path.Fill>
                        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                          <GradientStop Color="#4B86B2" Offset="0" />
                          <GradientStop Color="#477FA8" Offset="1" />
                        </LinearGradientBrush>
                      </Path.Fill>
                    </Path>
                  </Binding.FallbackValue>
                </Binding>
              </ContentControl.Content>
            </ContentControl>


            <Grid Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>

              <TextBlock x:Name="Title" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title, FallbackValue='Watch Now'}" Grid.Column="1" VerticalAlignment="Bottom" FontFamily="Calibri" FontWeight="Bold" FontSize="28" Foreground="White" Margin="20,0,0,0" />
              <TextBlock x:Name="SubTitle" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SubTitle, FallbackValue='Duration: 50 min'}" Grid.Column="1" Grid.Row="1" VerticalAlignment="top" FontFamily="Calibri" FontSize="14" Foreground="White" Margin="20,0,0,0" />
            </Grid>
          </Grid>
        </Border>
      </Grid>

      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter TargetName="Title" Property="TextDecorations" Value="Underline" />
          <Setter TargetName="SubTitle" Property="TextDecorations" Value="Underline" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
          <Setter TargetName="MainBorder" Property="Background">
            <Setter.Value>
              <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                <GradientStop Color="#FF5E5E5E" Offset="0" />
                <GradientStop Color="#FFA4A4A4" Offset="1" />
              </LinearGradientBrush>
            </Setter.Value>
          </Setter>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

Here's the code-behind:

using System.Windows;
using System.Windows.Controls;

namespace Controls
{
  public partial class FancyButton : Button
  {
    public FancyButton()
    {
      InitializeComponent();
    }

    public string Title
    {
      get { return (string)GetValue(TitleProperty); }
      set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("Title", FrameworkPropertyMetadataOptions.AffectsRender));

    public string SubTitle
    {
      get { return (string)GetValue(SubTitleProperty); }
      set { SetValue(SubTitleProperty, value); }
    }

    public static readonly DependencyProperty SubTitleProperty =
        DependencyProperty.Register("SubTitle", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("SubTitle", FrameworkPropertyMetadataOptions.AffectsRender));

    public FrameworkElement Image
    {
      get { return (FrameworkElement)GetValue(ImageProperty); }
      set { SetValue(ImageProperty, value); }
    }

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.Register("Image", typeof(FrameworkElement), typeof(FancyButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
  }
}

Here is how to use it:

<controls:FancyButton Grid.Row="1" HorizontalAlignment="Right" Margin="3" Title="Watch Now" SubTitle="Duration: 50 min">
  <controls:FancyButton.Image>
    <Path Data="M0,0 L30,15 L0,30Z">
      <Path.Effect>
        <DropShadowEffect Direction="50" ShadowDepth="2" />
      </Path.Effect>
      <Path.Fill>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
          <GradientStop Color="#4B86B2" Offset="0" />
          <GradientStop Color="#477FA8" Offset="1" />
        </LinearGradientBrush>
      </Path.Fill>
    </Path>
  </controls:FancyButton.Image>
</controls:FancyButton>

What's the bad magic number error?

This is much more efficent than above.

find {directory-of-.pyc-files} -name "*.pyc" -print0 | xargs -0 rm -rf

where {directory-of-.pyc-files} is the directory that contains the compiled python files.

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

Shift elements in a numpy array

You can also do this with Pandas:

Using a 2356-long array:

import numpy as np

xs = np.array([...])

Using scipy:

from scipy.ndimage.interpolation import shift

%timeit shift(xs, 1, cval=np.nan)
# 956 µs ± 77.9 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Using Pandas:

import pandas as pd

%timeit pd.Series(xs).shift(1).values
# 377 µs ± 9.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In this example, using Pandas was about ~8 times faster than Scipy

Set background image according to screen resolution

I know it's too old question but thought to answer, it might will help someone. If you see twitter, you will find something very tricky but pure css approach to achieve this.

<div class="background"><img src="home-bg.png" /></div>
Applied CSS
.background {
    background: none repeat scroll 0 0 #FFFFFF;
    height: 200%;
    left: -50%;
    position: fixed;
    width: 200%;}

.background img{
    bottom: 0;
    display: block;
    left: 0;
    margin: auto;
    min-height: 50%;
    min-width: 50%;
    right: 0;
    top: 0;}

This background images fits to all size. even portrait view of ipad. it always adjust the image in center. if you zoom out; image will remain the same.

Convert Month Number to Month Name Function in SQL

Use the Best way

Select DateName( month , DateAdd( month , @MonthNumber , -1 ))

Connecting to SQL Server with Visual Studio Express Editions

Workaround:

  1. Open your solution in Visual Web Developer Express. It will not load some of the projects in the solution but it is ok.
  2. Make a new connection in Database Explorer to the required database from SQL Server.
  3. Add a new class library project.
  4. Add a LINQ to SQL Classes item and link it to your database.
  5. Close the solution.
  6. Open the solution in Visual C# Express.

Now you have a LINQ to SQL classes library that is linked to your SQL Server database in Visual C# Express.

Update

The solution is for Visual Studio Express 2010.

TypeError: $(...).on is not a function

If you are using old version of jQuery(< 1.7) then you can use "bind" instead of "on". This will only work in case you are using old version, since as of jQuery 3.0, "bind" has been deprecated.

Npm install cannot find module 'semver'

This worked for me on Ubuntu (latest version dated Oct/2020)

I had to first get code from the bash source:

curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -

This got the latest version of node which updated my libraries and got rid of the 'semver' error.

How to declare a static const char* in your header file?

If you're using Visual C++, you can non-portably do this using hints to the linker...

// In foo.h...

class Foo
{
public:
   static const char *Bar;
};

// Still in foo.h; doesn't need to be in a .cpp file...

__declspec(selectany)
const char *Foo::Bar = "Blah";

__declspec(selectany) means that even though Foo::Bar will get declared in multiple object files, the linker will only pick up one.

Keep in mind this will only work with the Microsoft toolchain. Don't expect this to be portable.

Using NSPredicate to filter an NSArray based on NSDictionary keys

NSPredicate is only available in iPhone 3.0.

You won't notice that until try to run on device.

json_encode(): Invalid UTF-8 sequence in argument

Updated.. I solved this issue by stating the charset on PDO connection as below:

"mysql:host=$host;dbname=$db;charset=utf8"

All data received was then in the correct charset for the rest of the code to use

What is the use of ByteBuffer in Java?

Here is a great article explaining ByteBuffer benefits. Following are the key points in the article:

  • First advantage of a ByteBuffer irrespective of whether it is direct or indirect is efficient random access of structured binary data (e.g., low-level IO as stated in one of the answers). Prior to Java 1.4, to read such data one could use a DataInputStream, but without random access.

Following are benefits specifically for direct ByteBuffer/MappedByteBuffer. Note that direct buffers are created outside of heap:

  1. Unaffected by gc cycles: Direct buffers won't be moved during garbage collection cycles as they reside outside of heap. TerraCota's BigMemory caching technology seems to rely heavily on this advantage. If they were on heap, it would slow down gc pause times.

  2. Performance boost: In stream IO, read calls would entail system calls, which require a context-switch between user to kernel mode and vice versa, which would be costly especially if file is being accessed constantly. However, with memory-mapping this context-switching is reduced as data is more likely to be found in memory (MappedByteBuffer). If data is available in memory, it is accessed directly without invoking OS, i.e., no context-switching.

Note that MappedByteBuffers are very useful especially if the files are big and few groups of blocks are accessed more frequently.

  1. Page sharing: Memory mapped files can be shared between processes as they are allocated in process's virtual memory space and can be shared across processes.

How do I create HTML table using jQuery dynamically?

You may use two options:

  1. createElement
  2. InnerHTML

Create Element is the fastest way (check here.):

$(document.createElement('table'));

InnerHTML is another popular approach:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

Edit:

Check Dynamic creation of table with DOM

Edit 2:

IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

function createProviderFormFields(id, labelText, tooltip, regex) {
    var tr = '<tr>' ;
         // create a new textInputBox  
           var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
        // create a new Label Text
            tr += '<td>' + labelText  + '</td>';
            tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;
}

Using JQuery to check if no radio button in a group has been checked

Use .length refer to http://api.jquery.com/checked-selector/

if ($('input[name="html_elements"]:checked').length === 0) alert("Not checked");
else alert("Checked");

Get the IP Address of local computer

The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. Servers usually have more than one adapter.

Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine:

void ListIpAddresses(IpAddresses& ipAddrs)
{
  IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);
  IP_ADAPTER_ADDRESSES* adapter(NULL);

  // Start with a 16 KB buffer and resize if needed -
  // multiple attempts in case interfaces change while
  // we are in the middle of querying them.
  DWORD adapter_addresses_buffer_size = 16 * KB;
  for (int attempts = 0; attempts != 3; ++attempts)
  {
    adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);
    assert(adapter_addresses);

    DWORD error = ::GetAdaptersAddresses(
      AF_UNSPEC, 
      GAA_FLAG_SKIP_ANYCAST | 
        GAA_FLAG_SKIP_MULTICAST | 
        GAA_FLAG_SKIP_DNS_SERVER |
        GAA_FLAG_SKIP_FRIENDLY_NAME, 
      NULL, 
      adapter_addresses,
      &adapter_addresses_buffer_size);

    if (ERROR_SUCCESS == error)
    {
      // We're done here, people!
      break;
    }
    else if (ERROR_BUFFER_OVERFLOW == error)
    {
      // Try again with the new size
      free(adapter_addresses);
      adapter_addresses = NULL;

      continue;
    }
    else
    {
      // Unexpected error code - log and throw
      free(adapter_addresses);
      adapter_addresses = NULL;

      // @todo
      LOG_AND_THROW_HERE();
    }
  }

  // Iterate through all of the adapters
  for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)
  {
    // Skip loopback adapters
    if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
    {
      continue;
    }

    // Parse all IPv4 and IPv6 addresses
    for (
      IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; 
      NULL != address;
      address = address->Next)
    {
      auto family = address->Address.lpSockaddr->sa_family;
      if (AF_INET == family)
      {
        // IPv4
        SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);

        char str_buffer[INET_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);
        ipAddrs.mIpv4.push_back(str_buffer);
      }
      else if (AF_INET6 == family)
      {
        // IPv6
        SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);

        char str_buffer[INET6_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);

        std::string ipv6_str(str_buffer);

        // Detect and skip non-external addresses
        bool is_link_local(false);
        bool is_special_use(false);

        if (0 == ipv6_str.find("fe"))
        {
          char c = ipv6_str[2];
          if (c == '8' || c == '9' || c == 'a' || c == 'b')
          {
            is_link_local = true;
          }
        }
        else if (0 == ipv6_str.find("2001:0:"))
        {
          is_special_use = true;
        }

        if (! (is_link_local || is_special_use))
        {
          ipAddrs.mIpv6.push_back(ipv6_str);
        }
      }
      else
      {
        // Skip all other types of addresses
        continue;
      }
    }
  }

  // Cleanup
  free(adapter_addresses);
  adapter_addresses = NULL;

  // Cheers!
}

Resolving a Git conflict with binary files

You have to resolve the conflict manually (copying the file over) and then commit the file (no matter if you copied it over or used the local version) like this

git commit -a -m "Fix merge conflict in test.foo"

Git normally autocommits after merging, but when it detects conflicts it cannot solve by itself, it applies all patches it figured out and leaves the rest for you to resolve and commit manually. The Git Merge Man Page, the Git-SVN Crash Course or this blog entry might shed some light on how it's supposed to work.

Edit: See the post below, you don't actually have to copy the files yourself, but can use

git checkout --ours -- path/to/file.txt
git checkout --theirs -- path/to/file.txt

to select the version of the file you want. Copying / editing the file will only be necessary if you want a mix of both versions.

Please mark mipadis answer as the correct one.

How to read a text file in project's root directory?

You can use the following to get the root directory of a website project:

String FilePath;
FilePath = Server.MapPath("/MyWebSite");

Or you can get the base directory like so:

AppDomain.CurrentDomain.BaseDirectory

Determine if two rectangles overlap each other?

Java code to figure out if Rectangles are contacting or overlapping each other

...

for ( int i = 0; i < n; i++ ) {
    for ( int j = 0; j < n; j++ ) {
        if ( i != j ) {
            Rectangle rectangle1 = rectangles.get(i);
            Rectangle rectangle2 = rectangles.get(j);

            int l1 = rectangle1.l; //left
            int r1 = rectangle1.r; //right
            int b1 = rectangle1.b; //bottom
            int t1 = rectangle1.t; //top

            int l2 = rectangle2.l;
            int r2 = rectangle2.r;
            int b2 = rectangle2.b;
            int t2 = rectangle2.t;

            boolean topOnBottom = t2 == b1;
            boolean bottomOnTop = b2 == t1;
            boolean topOrBottomContact = topOnBottom || bottomOnTop;

            boolean rightOnLeft = r2 == l1;
            boolean leftOnRight = l2 == r1;
            boolean rightOrLeftContact = leftOnRight || rightOnLeft;

            boolean leftPoll = l2 <= l1 && r2 >= l1;
            boolean rightPoll = l2 <= r1 && r2 >= r1;
            boolean leftRightInside = l2 >= l1 && r2 <= r1;
            boolean leftRightPossiblePlaces = leftPoll || rightPoll || leftRightInside;

            boolean bottomPoll = t2 >= b1 && b2 <= b1;
            boolean topPoll = b2 <= b1 && t2 >= b1;
            boolean topBottomInside = b2 >= b1 && t2 <= t1;
            boolean topBottomPossiblePlaces = bottomPoll || topPoll || topBottomInside;


            boolean topInBetween = t2 > b1 && t2 < t1;
            boolean bottomInBetween = b2 > b1 && b2 < t1;
            boolean topBottomInBetween = topInBetween || bottomInBetween;

            boolean leftInBetween = l2 > l1 && l2 < r1;
            boolean rightInBetween = r2 > l1 && r2 < r1;
            boolean leftRightInBetween = leftInBetween || rightInBetween;

            if ( (topOrBottomContact && leftRightPossiblePlaces) || (rightOrLeftContact && topBottomPossiblePlaces) ) {
                path[i][j] = true;
            }
        }
    }
}

...

How to upload & Save Files with Desired name

Just get the file extention then assign the file a new name with uniqid and pass the new name to the move_upload_file method. For example:

if(isset($_POST['submit'])){
  $total = count($_FILES['files']['tmp_name']);
  for($i=0;$i<$total;$i++){
    $fileName = $_FILES['files']['name'][$i];
    $ext = pathinfo($fileName, PATHINFO_EXTENSION);
    $newFileName = uniqid();
    $fileDest = 'filesUploaded/'.$newFileName.'.'.$ext;
    if($ext === 'pdf' || 'jpeg' || 'JPG'){
        move_uploaded_file($_FILES['files']['tmp_name'][$i], $fileDest);
        $fileUpload = $newFileName.'.'.$ext[$i].',<br>';
    }else{
      echo 'Pdfs and jpegs only please';
    }
  }
}

How to change the color of an image on hover

If I understand correctly then it would be easier if you gave your image a transparent background and set the background container's background-color property without having to use filters and so on.

http://www.ajaxblender.com/howto-convert-image-to-grayscale-using-javascript.html

Shows you how to use filters in IE. Maybe if you leverage something from that. Not very cross-browser compatible though. Another option might be to have two images and use them as background-images (rather than img tags), swap one out after another using the :hover pseudo selector.

If REST applications are supposed to be stateless, how do you manage sessions?

Statelessness means that every HTTP request happens in complete isolation. When the client makes an HTTP request, it includes all the information necessary for the server to fulfill that request. The server never relies on information from previous requests. If that information was important, the client would have to send it again in subsequent request. Statelessness also brings new features. It’s easier to distribute a stateless application across load-balanced servers. A stateless application is also easy to cache.

There are actually two kinds of state. Application State that lives on the client and Resource State that lives on the server.

A web service only needs to care about your application state when you’re actually making a request. The rest of the time, it doesn’t even know you exist. This means that whenever a client makes a request, it must include all the application states the server will need to process it.

Resource state is the same for every client, and its proper place is on the server. When you upload a picture to a server, you create a new resource: the new picture has its own URI and can be the target of future requests. You can fetch, modify, and delete this resource through HTTP.

Hope this helps differentiate what statelessness and various states mean.

What are the differences between "=" and "<-" assignment operators in R?

The operators <- and = assign into the environment in which they are evaluated. The operator <- can be used anywhere, whereas the operator = is only allowed at the top level (e.g., in the complete expression typed at the command prompt) or as one of the subexpressions in a braced list of expressions.

How do I parse JSON with Objective-C?

Don't reinvent the wheel. Use json-framework or something similar.

If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:

SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];

// now you can grab data out of the dictionary using objectForKey or another dictionary method

return string with first match Regex

Maybe this would perform a bit better in case greater amount of input data does not contain your wanted piece because except has greater cost.

def return_first_match(text):
    result = re.findall('\d+',text)
    result = result[0] if result else ""
    return result

How can I delete all of my Git stashes at once?

There are two ways to delete a stash:

  1. If you no longer need a particular stash, you can delete it with: $ git stash drop <stash_id>.
  2. You can delete all of your stashes from the repo with: $ git stash clear.

Use both of them with caution, it maybe is difficult to revert the once deleted stashes.

Here is the reference article.

Switch: Multiple values in one case?

You can use ifelse instead.but if you want to know how to use switch in this case.here is an example.

int age = Convert.ToInt32(txtBoxAge.Text);`
int flag;
if(age >= 1 && age <= 8) {
flag = 1;
} else if (age >= 9 && age <= 15) {
 flag = 2;
} else if (age >= 16 && age <= 100) {
 flag = 3;
} else {
 flag = 4;   
}
switch (flag) 

{
 case 1:
  MessageBox.Show("You are only " + age + " years old\n You must be kidding right.\nPlease fill in your *real* age.");
break;
case 2:
  MessageBox.Show("You are only " + age + " years old\n That's too young!");
break;
case 3:
  MessageBox.Show("You are " + age + " years old\n Perfect.");
break;
default:
  MessageBox.Show("You an old person.");
break;
}

hope that helps ! :)

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

remove item from array using its name / value

Try this:

var COUNTRY_ID = 'AL';

countries.results = 
  countries.results.filter(function(el){ return el.id != COUNTRY_ID; });

Store an array in HashMap

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();

pick one, for example

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
    map.get("Something").add(coeficientUzura[i]); 
}

or just

HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);

Joda DateTime to Timestamp conversion

//This Works just fine
DateTime dt = new DateTime();
Log.d("ts",String.valueOf(dt.now()));               
dt=dt.plusYears(3);
dt=dt.minusDays(7);
Log.d("JODA DateTime",String.valueOf(dt));
Timestamp ts= new Timestamp(dt.getMillis());
Log.d("Coverted to java.sql.Timestamp",String.valueOf(ts));

Linq : select value in a datatable column

I notice others have given the non-lambda syntax so just to have this complete I'll put in the lambda syntax equivalent:

Non-lambda (as per James's post):

var name = from i in DataContext.MyTable
           where i.ID == 0
           select i.Name

Equivalent lambda syntax:

var name = DataContext.MyTable.Where(i => i.ID == 0)
                              .Select(i => new { Name = i.Name });

There's not really much practical difference, just personal opinion on which you prefer.

"Permission Denied" trying to run Python on Windows 10

This appears to be a limitation in git-bash. The recommendation to use winpty python.exe worked for me. See Python not working in the command line of git bash for additional information.

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

How to get current date time in milliseconds in android

I think leverage this functionality using Java

long time= System.currentTimeMillis();

this will return current time in milliseconds mode . this will surely work

long time= System.currentTimeMillis();
android.util.Log.i("Time Class ", " Time value in millisecinds "+time);

Here is my logcat using the above function

05-13 14:38:03.149: INFO/Time Class(301): Time value in millisecinds 1368436083157

If you got any doubt with millisecond value .Check Here

EDIT : Time Zone I used to demo the code IST(+05:30) ,So if you check milliseconds that mentioned in log to match with time in log you might get a different value based your system timezone

EDIT: This is easy approach .but if you need time zone or any other details I think this won't be enough Also See this approach using android api support

How to find the index of an element in an int array?

static int[] getIndex(int[] data, int number) {
    int[] positions = new int[data.length];
    if (data.length > 0) {
        int counter = 0;
        for(int i =0; i < data.length; i++) {
            if(data[i] == number){
                positions[counter] = i;
                counter++;
            }
        }
    }
    return positions;
}

How to order citations by appearance using BibTeX?

I use natbib in combination with bibliographystyle{apa}. Eg:

\begin{document}

The body of the document goes here...

\newpage

\bibliography{bibliography} % Or whatever you decided to call your .bib file 

\usepackage[round, comma, sort&compress ]{natbib} 

bibliographystyle{apa}
\end{document}

Converting a string to a date in a cell

Have you tried the =DateValue() function?

To include time value, just add the functions together:

=DateValue(A1)+TimeValue(A1)

Make body have 100% of the browser height

You can also use JS if needed

var winHeight = window.innerHeight    || 
document.documentElement.clientHeight || 
document.body.clientHeight;

var pageHeight = $('body').height();
if (pageHeight < winHeight) {
    $('.main-content,').css('min-height',winHeight)
}

Angularjs if-then-else construction in expression

This can be done in one line.

{{corretor.isAdministrador && 'YES' || 'NÂO'}}

Usage in a td tag:

<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>

Is there a better jQuery solution to this.form.submit();?

Similar to Matthew's answer, I just found that you can do the following:

$(this).closest('form').submit();

Wrong: The problem with using the parent functionality is that the field needs to be immediately within the form to work (not inside tds, labels, etc).

I stand corrected: parents (with an s) also works. Thxs Paolo for pointing that out.

Is it possible to install iOS 6 SDK on Xcode 5?

I currently have Xcode 4.6.3 and 5.0 installed. I used the following bash script to link 5.0 to the SDKs in the old version:

platforms_path="$1/Contents/Developer/Platforms";
if [ -d $platforms_path ]; then
    for platform in `ls $platforms_path`
    do
        sudo ln -sf $platforms_path/$platform/Developer/SDKs/* $(xcode-select --print-path)/Platforms/$platform/Developer/SDKs;
    done;
fi;

You just need to supply it with the path to the .app:

./xcode.sh /Applications/Xcode-463.app

System.Timers.Timer vs System.Threading.Timer

Information from Microsoft about this (see Remarks on MSDN):

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

It is interesting to mention that System.Timers.Timer was deprecated with .NET Core 1.0, but was implemented again in .NET Core 2.0 (/ .NET Standard 2.0). The goal with .NET Standard 2.0 was that it should be as easy as possible to switch from the .NET Framework which is probably the reason it came back.

When it was deprecated, the .NET Portability Analyzer Visual Studio Add-In recommended to use System.Threading.Timer instead.

Looks like that Microsoft favors System.Threading.Timer before System.Timers.Timer.

EDIT NOTE 2018-11-15: I hand to change my answer since the old information about .NET Core 1.0 was not valid anymore.

How to pass multiple parameters in a querystring

Query_string

(Following is the text of the linked section of the Wikipedia entry.)

Structure

A typical URL containing a query string is as follows:

http://server/path/program?query_string

When a server receives a request for such a page, it runs a program (if configured to do so), passing the query_string unchanged to the program. The question mark is used as a separator and is not part of the query string.

A link in a web page may have a URL that contains a query string, however, HTML defines three ways a web browser can generate the query string:

  • a web form via the ... element
  • a server-side image map via the ?ismap? attribute on the element with a construction
  • an indexed search via the now deprecated element

Web forms

The main use of query strings is to contain the content of an HTML form, also known as web form. In particular, when a form containing the fields field1, field2, field3 is submitted, the content of the fields is encoded as a query string as follows:

field1=value1&field2=value2&field3=value3...

  • The query string is composed of a series of field-value pairs.
  • Within each pair, the field name and value are separated by an equals sign. The equals sign may be omitted if the value is an empty string.
  • The series of pairs is separated by the ampersand, '&' (or semicolon, ';' for URLs embedded in HTML and not generated by a ...; see below). While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field:

field1=value1&field1=value2&field1=value3...

For each field of the form, the query string contains a pair field=value. Web forms may include fields that are not visible to the user; these fields are included in the query string when the form is submitted

This convention is a W3C recommendation. W3C recommends that all web servers support semicolon separators in addition to ampersand separators[6] to allow application/x-www-form-urlencoded query strings in URLs within HTML documents without having to entity escape ampersands.

Technically, the form content is only encoded as a query string when the form submission method is GET. The same encoding is used by default when the submission method is POST, but the result is not sent as a query string, that is, is not added to the action URL of the form. Rather, the string is sent as the body of the HTTP request.

Oracle - Why does the leading zero of a number disappear when converting it TO_CHAR

Below format try if number is like

ex 1 suppose number like 10.1 if apply below format it will be come as 10.10

ex 2 suppose number like .02 if apply below format it will be come as 0.02

ex 3 suppose number like 0.2 if apply below format it will be come as 0.20

to_char(round(to_number(column_name)/10000000,2),'999999999990D99') as column_name

How do I sort a VARCHAR column in SQL server that contains numbers?

One possible solution is to pad the numeric values with a character in front so that all are of the same string length.

Here is an example using that approach:

select MyColumn
from MyTable
order by 
    case IsNumeric(MyColumn) 
        when 1 then Replicate('0', 100 - Len(MyColumn)) + MyColumn
        else MyColumn
    end

The 100 should be replaced with the actual length of that column.

Return multiple values from a function, sub or type?

I always approach returning more than one result from a function by always returning an ArrayList. By using an ArrayList I can return only one item, consisting of many multiple values, mixing between Strings and Integers.

Once I have the ArrayList returned in my main sub, I simply use ArrayList.Item(i).ToString where i is the index of the value I want to return from the ArrayList

An example:

 Public Function Set_Database_Path()
        Dim Result As ArrayList = New ArrayList
        Dim fd As OpenFileDialog = New OpenFileDialog()


        fd.Title = "Open File Dialog"
        fd.InitialDirectory = "C:\"
        fd.RestoreDirectory = True
        fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
        fd.FilterIndex = 2
        fd.Multiselect = False


        If fd.ShowDialog() = DialogResult.OK Then

            Dim Database_Location = Path.GetFullPath(fd.FileName)

            Dim Database_Connection_Var = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" & Database_Location & """"

            Result.Add(Database_Connection_Var)
            Result.Add(Database_Location)

            Return (Result)

        Else

            Return (Nothing)

        End If
    End Function

And then call the Function like this:

Private Sub Main_Load()
  Dim PathArray As ArrayList

            PathArray = Set_Database_Path()
            My.Settings.Database_Connection_String = PathArray.Item(0).ToString
            My.Settings.FilePath = PathArray.Item(1).ToString
            My.Settings.Save()
End Sub

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In your entity definition, you're not specifying the @JoinColumn for the Account joined to a Transaction. You'll want something like this:

@Entity
public class Transaction {
    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    @JoinColumn(name = "accountId", referencedColumnName = "id")
    private Account fromAccount;
}

EDIT: Well, I guess that would be useful if you were using the @Table annotation on your class. Heh. :)

Submit HTML form on self page

Use ?:

<form action="?" method="post">

It will send the user back to the same page.

Insert/Update/Delete with function in SQL Server

Just another alternative using sp_executesql (tested only in SQL 2016). As previous posts noticed, atomicity must be handled elsewhere.

CREATE FUNCTION [dbo].[fn_get_service_version_checksum2]
(
    @ServiceId INT
)
RETURNS INT
AS
BEGIN
DECLARE @Checksum INT;
SELECT @Checksum = dbo.fn_get_service_version(@ServiceId);
DECLARE @LatestVersion INT = (SELECT MAX(ServiceVersion) FROM [ServiceVersion] WHERE ServiceId = @ServiceId);
-- Check whether the current version already exists and that it's the latest version.
IF EXISTS(SELECT TOP 1 1 FROM [ServiceVersion] WHERE ServiceId = @ServiceId AND [Checksum] = @Checksum AND ServiceVersion = @LatestVersion)
    RETURN @LatestVersion;
-- Insert the new version to the table.
EXEC sp_executesql N'
INSERT INTO [ServiceVersion] (ServiceId, ServiceVersion, [Checksum], [Timestamp])
VALUES (@ServiceId, @LatestVersion + 1, @Checksum, GETUTCDATE());',
N'@ServiceId INT = NULL, @LatestVersion INT = NULL, @Checksum INT = NULL',
@ServiceId = @ServiceId,
@LatestVersion = @LatestVersion,
@Checksum = @Checksum
;
RETURN @LatestVersion + 1;
END;

Cookies vs. sessions

Short answer

Rules ordered by priority:

  • Rule 1. Never trust user input : cookies are not safe. Use sessions for sensitive data.
  • Rule 2. If persistent data must remain when the user closes the browser, use cookies.
  • Rule 3. If persistent data does not have to remain when the user closes the browser, use sessions.
  • Rule 4. Read the detailed answer!

Source : https://www.lucidar.me/en/web-dev/sessions-or-cookies/


Detailed answer

Cookies

  • Cookies are stored on the client side (in the visitor's browser).
  • Cookies are not safe: it's quite easy to read and write cookie contents.
  • When using cookies, you have to notify visitors according to european laws (GDPR).
  • Expiration can be set, but user or browser can change it.
  • Users (or browser) can (be set to) decline the use of cookies.

Sessions

  • Sessions are stored on the server side.
  • Sessions use cookies (see below).
  • Sessions are safer than cookies, but not invulnarable.
  • Expiration is set in server configuration (php.ini for example).
  • Default expiration time is 24 minutes or when the browser is closed.
  • Expiration is reset when the user refreshes or loads a new page.
  • Users (or browser) can (be set to) decline the use of cookies, therefore sessions.
  • Legally, you also have to notify visitors for the cookie, but the lack of precedent is not clear yet.

The appropriate choice

Sessions use a cookie! Session data is stored on the server side, but a UID is stored on client side in a cookie. It allows the server to match a given user with the right session data. UID is protected and hard to hack, but not invulnarable. For sensitive actions (changing email or resetting password), do not rely on sessions neither cookies : ask for the user password to confirm the action.

Sensitive data should never be stored in cookies (emails, encrypted passwords, personal data ...). Keep in mind the data are stored on a foreign computer, and if the computer is not private (classroom or public computers) someone else can potentially read the cookies content.

Remember-me data must be stored in cookies, otherwise data will be lost when the user closes the browser. However, don't save password or user personal data in the 'remember-me' cookie. Store user data in database and link this data with an encrypted pair of ID / key stored in a cookie.

After considering the previous recommandations, the following question is finally what helps you choosing between cookies and sessions:

Must persistent data remain when the user closes the browser ?

  • If the answer is yes, use cookies.
  • If the answer is no, use sessions.

Alternative to itoa() for converting integer to string C++?

On Windows CE derived platforms, there are no iostreams by default. The way to go there is preferaby with the _itoa<> family, usually _itow<> (since most string stuff are Unicode there anyway).

Passing string to a function in C - with or without pointers?

The accepted convention of passing C-strings to functions is to use a pointer:

void function(char* name)

When the function modifies the string you should also pass in the length:

void function(char* name, size_t name_length)

Your first example:

char *functionname(char *string name[256])

passes an array of pointers to strings which is not what you need at all.

Your second example:

char functionname(char string[256])

passes an array of chars. The size of the array here doesn't matter and the parameter will decay to a pointer anyway, so this is equivalent to:

char functionname(char *string)

See also this question for more details on array arguments in C.

UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only

The answer of Shyam was right. I already faced with this issue before. It's not a problem, it's a SPRING feature. "Transaction rolled back because it has been marked as rollback-only" is acceptable.

Conclusion

  • USE REQUIRES_NEW if you want to commit what did you do before exception (Local commit)
  • USE REQUIRED if you want to commit only when all processes are done (Global commit) And you just need to ignore "Transaction rolled back because it has been marked as rollback-only" exception. But you need to try-catch out side the caller processNextRegistrationMessage() to have a meaning log.

Let's me explain more detail:

Question: How many Transaction we have? Answer: Only one

Because you config the PROPAGATION is PROPAGATION_REQUIRED so that the @Transaction persist() is using the same transaction with the caller-processNextRegistrationMessage(). Actually, when we get an exception, the Spring will set rollBackOnly for the TransactionManager so the Spring will rollback just only one Transaction.

Question: But we have a try-catch outside (), why does it happen this exception? Answer Because of unique Transaction

  1. When persist() method has an exception
  2. Go to the catch outside

    Spring will set the rollBackOnly to true -> it determine we must 
    rollback the caller (processNextRegistrationMessage) also.
    
  3. The persist() will rollback itself first.

  4. Throw an UnexpectedRollbackException to inform that, we need to rollback the caller also.
  5. The try-catch in run() will catch UnexpectedRollbackException and print the stack trace

Question: Why we change PROPAGATION to REQUIRES_NEW, it works?

Answer: Because now the processNextRegistrationMessage() and persist() are in the different transaction so that they only rollback their transaction.

Thanks

C/C++ macro string concatenation

You don't need that sort of solution for string literals, since they are concatenated at the language level, and it wouldn't work anyway because "s""1" isn't a valid preprocessor token.

[Edit: In response to the incorrect "Just for the record" comment below that unfortunately received several upvotes, I will reiterate the statement above and observe that the program fragment

#define PPCAT_NX(A, B) A ## B
PPCAT_NX("s", "1")

produces this error message from the preprocessing phase of gcc: error: pasting ""s"" and ""1"" does not give a valid preprocessing token

]

However, for general token pasting, try this:

/*
 * Concatenate preprocessor tokens A and B without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define PPCAT_NX(A, B) A ## B

/*
 * Concatenate preprocessor tokens A and B after macro-expanding them.
 */
#define PPCAT(A, B) PPCAT_NX(A, B)

Then, e.g., both PPCAT_NX(s, 1) and PPCAT(s, 1) produce the identifier s1, unless s is defined as a macro, in which case PPCAT(s, 1) produces <macro value of s>1.

Continuing on the theme are these macros:

/*
 * Turn A into a string literal without expanding macro definitions
 * (however, if invoked from a macro, macro arguments are expanded).
 */
#define STRINGIZE_NX(A) #A

/*
 * Turn A into a string literal after macro-expanding it.
 */
#define STRINGIZE(A) STRINGIZE_NX(A)

Then,

#define T1 s
#define T2 1
STRINGIZE(PPCAT(T1, T2)) // produces "s1"

By contrast,

STRINGIZE(PPCAT_NX(T1, T2)) // produces "T1T2"
STRINGIZE_NX(PPCAT_NX(T1, T2)) // produces "PPCAT_NX(T1, T2)"

#define T1T2 visit the zoo
STRINGIZE(PPCAT_NX(T1, T2)) // produces "visit the zoo"
STRINGIZE_NX(PPCAT(T1, T2)) // produces "PPCAT(T1, T2)"

Why does SSL handshake give 'Could not generate DH keypair' exception?

I have the same problem with Yandex Maps server, JDK 1.6 and Apache HttpClient 4.2.1. The error was

javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

with enabled debug by -Djavax.net.debug=all there was a message in a log

Could not generate DH keypair

I have fixed this problem by adding BouncyCastle library bcprov-jdk16-1.46.jar and registering a provider in a map service class

public class MapService {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    public GeocodeResult geocode() {

    }

}

A provider is registered at the first usage of MapService.

Draw an X in CSS

single element solution:enter image description here

_x000D_
_x000D_
body{_x000D_
    background:blue;_x000D_
}_x000D_
_x000D_
div{_x000D_
    width:40px;_x000D_
    height:40px;_x000D_
    background-color:red;_x000D_
    position:relative;_x000D_
    border-radius:6px;_x000D_
    box-shadow:2px 2px 4px 0 white;_x000D_
}_x000D_
_x000D_
div:before,div:after{_x000D_
    content:'';_x000D_
    position:absolute;_x000D_
    width:36px;_x000D_
    height:4px;_x000D_
    background-color:white;_x000D_
    border-radius:2px;_x000D_
    top:16px;_x000D_
    box-shadow:0 0 2px 0 #ccc;_x000D_
}_x000D_
_x000D_
div:before{_x000D_
    -webkit-transform:rotate(45deg);_x000D_
    -moz-transform:rotate(45deg);_x000D_
    transform:rotate(45deg);_x000D_
    left:2px;_x000D_
}_x000D_
div:after{_x000D_
    -webkit-transform:rotate(-45deg);_x000D_
    -moz-transform:rotate(-45deg);_x000D_
    transform:rotate(-45deg);_x000D_
    right:2px;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Are there benefits of passing by pointer over passing by reference in C++?

Most of the answers here fail to address the inherent ambiguity in having a raw pointer in a function signature, in terms of expressing intent. The problems are the following:

  • The caller does not know whether the pointer points to a single objects, or to the start of an "array" of objects.

  • The caller does not know whether the pointer "owns" the memory it points to. IE, whether or not the function should free up the memory. (foo(new int) - Is this a memory leak?).

  • The caller does not know whether or not nullptr can be safely passed into the function.

All of these problems are solved by references:

  • References always refer to a single object.

  • References never own the memory they refer to, they are merely a view into memory.

  • References can't be null.

This makes references a much better candidate for general use. However, references aren't perfect - there are a couple of major problems to consider.

  • No explicit indirection. This is not a problem with a raw pointer, as we have to use the & operator to show that we are indeed passing a pointer. For example, int a = 5; foo(a); It is not clear at all here that a is being passed by reference and could be modified.
  • Nullability. This weakness of pointers can also be a strength, when we actually want our references to be nullable. Seeing as std::optional<T&> isn't valid (for good reasons), pointers give us that nullability you want.

So it seems that when we want a nullable reference with explicit indirection, we should reach for a T* right? Wrong!

Abstractions

In our desperation for nullability, we may reach for T*, and simply ignore all of the shortcomings and semantic ambiguity listed earlier. Instead, we should reach for what C++ does best: an abstraction. If we simply write a class that wraps around a pointer, we gain the expressiveness, as well as the nullability and explicit indirection.

template <typename T>
struct optional_ref {
  optional_ref() : ptr(nullptr) {}
  optional_ref(T* t) : ptr(t) {}
  optional_ref(std::nullptr_t) : ptr(nullptr) {}

  T& get() const {
    return *ptr;
  }

  explicit operator bool() const {
    return bool(ptr);
  }

private:
  T* ptr;
};

This is the most simple interface I could come up with, but it does the job effectively. It allows for initializing the reference, checking whether a value exists and accessing the value. We can use it like so:

void foo(optional_ref<int> x) {
  if (x) {
    auto y = x.get();
    // use y here
  }
}

int x = 5;
foo(&x); // explicit indirection here
foo(nullptr); // nullability

We have acheived our goals! Let's now see the benefits, in comparison to the raw pointer.

  • The interface shows clearly that the reference should only refer to one object.
  • Clearly it does not own the memory it refers to, as it has no user defined destructor and no method to delete the memory.
  • The caller knows nullptr can be passed in, since the function author explicitly is asking for an optional_ref

We could make the interface more complex from here, such as adding equality operators, a monadic get_or and map interface, a method that gets the value or throws an exception, constexpr support. That can be done by you.

In conclusion, instead of using raw pointers, reason about what those pointers actually mean in your code, and either leverage a standard library abstraction or write your own. This will improve your code significantly.

SQL query for getting data for last 3 months

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,

DATE_ADD(NOW(),INTERVAL -90 DAY) 
DATE_ADD(NOW(), INTERVAL -3 MONTH)

How to remove error about glyphicons-halflings-regular.woff2 not found

I tried all the suggestions above, but my actual issue was that my application was looking for the /font folder and its contents (.woff etc) in app/fonts, but my /fonts folder was on the same level as /app. I moved /fonts under /app, and it works fine now. I hope this helps someone else roaming the web for an answer.

There are No resources that can be added or removed from the server

I used mvn eclipse:eclipse -Dwtpversion=2.0 in command line in the folder where I had my pom.xml. Then I refreshed the project in eclipse IDE. After that I was able to add my project.

Convert columns to string in Pandas

Using .apply() with a lambda conversion function also works in this case:

total_rows['ColumnID'] = total_rows['ColumnID'].apply(lambda x: str(x))

For entire dataframes you can use .applymap(). (but in any case probably .astype() is faster)

Difference in System. exit(0) , System.exit(-1), System.exit(1 ) in Java

A non-zero exit status code, usually indicates abnormal termination. if n != 0, its up to the programmer to apply a meaning to the various n's.

From https://docs.oracle.com/javase/7/docs/api/java/lang/System.html.

TestNG ERROR Cannot find class in classpath

In my case, the package structure was not proper, it was like folders and sub-folders. I deleted that project and imported again with changing the respective jre. After that it worked for me. e.g. Folder structure- TestProject -TestSuite1 Package Structure- TestProject.TestSuite1

Is there a Python Library that contains a list of all the ascii characters?

You can do this without a module:

    characters = list(map(chr, range(97,123)))

Type characters and it should print ["a","b","c", ... ,"x","y","z"]. For uppercase use:

    characters=list(map(chr,range(65,91)))

Any range (including the use of range steps) can be used for this, because it makes use of Unicode. Therefore, increase the range() to add more characters to the list.
map() calls chr() every iteration of the range().

Center content vertically on Vuetify

In Vuetify 2.x, v-layout and v-flex are replaced by v-row and v-col respectively. To center the content both vertically and horizontally, we have to instruct the v-row component to do it:

<v-container fill-height>
    <v-row justify="center" align="center">
        <v-col cols="12" sm="4">
            Centered both vertically and horizontally
        </v-col>
    </v-row>
</v-container>
  • align="center" will center the content vertically inside the row
  • justify="center" will center the content horizontally inside the row
  • fill-height will center the whole content compared to the page.

Convert a Unix timestamp to time in JavaScript

// Format value as two digits 0 => 00, 1 => 01
function twoDigits(value) {
   if(value < 10) {
    return '0' + value;
   }
   return value;
}

var date = new Date(unix_timestamp*1000);
// display in format HH:MM:SS
var formattedTime = twoDigits(date.getHours()) 
      + ':' + twoDigits(date.getMinutes()) 
      + ':' + twoDigits(date.getSeconds());

How do I change file permissions in Ubuntu

If you just want to change file permissions, you want to be careful about using -R on chmod since it will change anything, files or folders. If you are doing a relative change (like adding write permission for everyone), you can do this:

sudo chmod -R a+w /var/www

But if you want to use the literal permissions of read/write, you may want to select files versus folders:

sudo find /var/www -type f -exec chmod 666 {} \;

(Which, by the way, for security reasons, I wouldn't recommend either of these.)

Or for folders:

sudo find /var/www -type d -exec chmod 755 {} \;

Limiting number of displayed results when using ngRepeat

store all your data initially

function PhoneListCtrl($scope, $http) {
  $http.get('phones/phones.json').success(function(data) {
    $scope.phones = data.splice(0, 5);
    $scope.allPhones = data;
  });

  $scope.orderProp = 'age';
  $scope.howMany = 5;
  //then here watch the howMany variable on the scope and update the phones array accordingly
  $scope.$watch("howMany", function(newValue, oldValue){
    $scope.phones = $scope.allPhones.splice(0,newValue)
  });
}

EDIT had accidentally put the watch outside the controller it should have been inside.

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

How can I store JavaScript variable output into a PHP variable?

in your view:

  <?php $value = '<p id="course_id"></p>';?>

javascript code:

  var course = document.getElementById("courses").value;
  
 document.getElementById("course_id").innerHTML = course;

Comparing floating point number to zero

No.

Equality is equality.

The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.

If you really want to test two doubles for equality, use this one:

inline bool isEqual(double x, double y)
{
   return x == y;
}

Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y is the code you want.

10.000000000000001 is not equal to 10.0, no matter what they tell you.

An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:

const double NO_DATA = -1.0;

double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);

if (myData != NO_DATA)
{
    ...
}

How do I tell what type of value is in a Perl variable?

I like polymorphism instead of manually checking for something:

use MooseX::Declare;

class Foo {
    use MooseX::MultiMethods;

    multi method foo (ArrayRef $arg){ say "arg is an array" }
    multi method foo (HashRef $arg) { say "arg is a hash" }
    multi method foo (Any $arg)     { say "arg is something else" }
}

Foo->new->foo([]); # arg is an array
Foo->new->foo(40); # arg is something else

This is much more powerful than manual checking, as you can reuse your "checks" like you would any other type constraint. That means when you want to handle arrays, hashes, and even numbers less than 42, you just write a constraint for "even numbers less than 42" and add a new multimethod for that case. The "calling code" is not affected.

Your type library:

package MyApp::Types;
use MooseX::Types -declare => ['EvenNumberLessThan42'];
use MooseX::Types::Moose qw(Num);

subtype EvenNumberLessThan42, as Num, where { $_ < 42 && $_ % 2 == 0 };

Then make Foo support this (in that class definition):

class Foo {
    use MyApp::Types qw(EvenNumberLessThan42);

    multi method foo (EvenNumberLessThan42 $arg) { say "arg is an even number less than 42" }
}

Then Foo->new->foo(40) prints arg is an even number less than 42 instead of arg is something else.

Maintainable.

How to navigate through textfields (Next / Done Buttons)

This is an old post, but has a high page rank so I'll chime in with my solution.

I had a similar issue and ended up creating a subclass of UIToolbar to manage the next/previous/done functionality in a dynamic tableView with sections: https://github.com/jday001/DataEntryToolbar

You set the toolbar as inputAccessoryView of your text fields and add them to its dictionary. This allows you to cycle through them forwards and backwards, even with dynamic content. There are delegate methods if you want to trigger your own functionality when textField navigation happens, but you don't have to deal with managing any tags or first responder status.

There are code snippets & an example app at the GitHub link to help with the implementation details. You will need your own data model to keep track of the values inside the fields.

How to replace innerHTML of a div using jQuery?

jQuery has few functions which work with text, if you use text() one, it will do the job for you:

$("#regTitle").text("Hello World");

Also, you can use html() instead, if you have any html tag...

mysqldump & gzip commands to properly create a compressed file of a MySQL database using crontab

You can use the tee command to redirect output:

/usr/bin/mysqldump -u user -pupasswd my-database | \
tee >(gzip -9 -c > /home/user/backup/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz)  | \
gzip> /home/user/backup2/mydatabase-backup-`date +\%m\%d_\%Y`.sql.gz 2>&1

see documentation here

Stop form refreshing page on submit

One great way to prevent reloading the page when submitting using a form is by adding return false with your onsubmit attribute.

<form action="#" onsubmit="yourJsFunction();return false">
    <input type="text"/>
    <input type="submit"/>
</form>

How to redirect in a servlet filter?

I'm trying to find a method to redirect my request from filter to login page

Don't

You just invoke

chain.doFilter(request, response);

from filter and the normal flow will go ahead.

I don't know how to redirect from servlet

You can use

response.sendRedirect(url);

to redirect from servlet

How to make a UILabel clickable?

Swift 3 Update

Replace

Selector("tapFunction:")

with

#selector(DetailViewController.tapFunction)

Example:

class DetailViewController: UIViewController {

    @IBOutlet weak var tripDetails: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        ...

        let tap = UITapGestureRecognizer(target: self, action: #selector(DetailViewController.tapFunction))
        tripDetails.isUserInteractionEnabled = true
        tripDetails.addGestureRecognizer(tap)
    }

    @objc
    func tapFunction(sender:UITapGestureRecognizer) {
        print("tap working")
    }
}

How do I debug Node.js applications?

The V8 debugger released as part of the Google Chrome Developer Tools can be used to debug Node.js scripts. A detailed explanation of how this works can be found in the Node.js GitHub wiki.

Ruby value of a hash key?

As an addition to e.g. @Intrepidd s answer, in certain situations you want to use fetch instead of []. For fetch not to throw an exception when the key is not found, pass it a default value.

puts "ok" if hash.fetch('key', nil) == 'X'

Reference: https://docs.ruby-lang.org/en/2.3.0/Hash.html .

Dynamic variable names in Bash

For zsh (newers mac os versions), you should use

real_var="holaaaa"
aux_var="real_var"
echo ${(P)aux_var}
holaaaa

Instead of "!"

How to display all elements in an arraylist?

Arraylist uses Iterator interface to traverse the elements Use this

public void display(ArrayList<Integer> v) {
        Iterator vEnum = v.iterator();
        System.out.println("\nElements in vector:");
        while (vEnum.hasNext()) {
            System.out.print(vEnum.next() + " ");
        }
    }

How to store images in mysql database using php

insert image zh

-while we insert image in database using insert query

$Image = $_FILES['Image']['name'];
    if(!$Image)
    {
      $Image="";
    }
    else
    {
      $file_path = 'upload/';
      $file_path = $file_path . basename( $_FILES['Image']['name']);    
      if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path)) 
     { 
}
}

How to print all session variables currently set?

Echo the session object as json. I like json because I have a browser extension that nicely formats json.

session_start();
echo json_encode($_SESSION);

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

C# Change A Button's Background Color

I doubt if any of those should work. Try: First import the namespace in the beginning of the code page as below.

using System.Drawing;

then in the code.

Button4.BackColor = Color.LawnGreen;

Hope it helps.

How to check if the given string is palindrome?

This is all good, but is there a way to do better algorithmically? I was once asked in a interview to recognize a palindrome in linear time and constant space.

I couldn't think of anything then and I still can't.

(If it helps, I asked the interviewer what the answer was. He said you can construct a pair of hash functions such that they hash a given string to the same value if and only if that string is a palindrome. I have no idea how you would actually make this pair of functions.)

How do I run msbuild from the command line using Windows SDK 7.1?

From Visual Studio 2013 onwards, MSbuild comes as a part of Visual Studio. Earlier, MSBuild was installed as a part of. NET Framework.

MSBuild is installed directly under %ProgramFiles%. So, the path for MSBuild might be different depending on the version of Visual Studio.

For Visual Studio 2015, Path of MSBuild is "%ProgramFiles(x86)%\MSBuild\14.0\Bin\MSBuild.exe"

For Visual Studio 15 Preview, Path of MSBuild is "%ProgramFiles(x86)%\MSBuild\15.0\Bin\MSBuild.exe"

Also, Some new MSBuild properties has been added and some have been modified. For more information look here

Update 1: VS 2017

The location for the MSBuild has changed again with the release of Visual Studio 2017. Now the installation directory is under the %ProgramFiles(x86)%\Microsoft Visual Studio\2017\[VS Edition]\MSBuild\15.0\Bin\. Since, i have an Enterprise edition, the MSBuild location for my machine is "%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\MSbuild.exe"

Importing variables from another file?

first.py:

a=5

second.py:

import first
print(first.a)

The result will be 5.

Regular expression to limit number of characters to 10

You can use curly braces to control the number of occurrences. For example, this means 0 to 10:

/^[a-z]{0,10}$/

The options are:

  • {3} Exactly 3 occurrences;
  • {6,} At least 6 occurrences;
  • {2,5} 2 to 5 occurrences.

See the regular expression reference.

Your expression had a + after the closing curly brace, hence the error.

Injecting $scope into an angular service function()

You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.

The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,

var students = $http.get(path).then(function (resp) {
  return resp.data;
}); // then() returns a promise object, not resp.data

There's a simple way to get around this and it's to supply a callback function.

.service('StudentService', [ '$http',
    function ($http) {
    // get some data via the $http
    var path = '/students';

    //save method create a new student if not already exists
    //else update the existing object
    this.save = function (student, doneCallback) {
      $http.post(
        path, 
        {
          params: {
            student: student
          }
        }
      )
      .then(function (resp) {
        doneCallback(resp.data); // when the async http call is done, execute the callback
      });  
    }
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
  $scope.saveUser = function (user) {
    StudentService.save(user, function (data) {
      $scope.message = data; // I'm assuming data is a string error returned from your REST API
    })
  }
}]);

The form:

<div class="form-message">{{message}}</div>

<div ng-controller="StudentSaveController">
  <form novalidate class="simple-form">
    Name: <input type="text" ng-model="user.name" /><br />
    E-mail: <input type="email" ng-model="user.email" /><br />
    Gender: <input type="radio" ng-model="user.gender" value="male" />male
    <input type="radio" ng-model="user.gender" value="female" />female<br />
    <input type="button" ng-click="reset()" value="Reset" />
    <input type="submit" ng-click="saveUser(user)" value="Save" />
  </form>
</div>

This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.

How to generate a random number between 0 and 1?

Have you tried with: replacing ((rand() % 10000) / 10000.0), with:(rand() % 2). This worked for me!

So you could do something like this:

double r2()
{
     srand(time(NULL));
     return(rand() % 2);
}

Run git pull over all subdirectories

Original answer 2010:

If all of those directories are separate git repo, you should reference them as submodules.

That means your "origin" would be that remote repo 'plugins' which only contains references to subrepos 'cms', 'admin', 'chart'.

A git pull followed by a git submodule update would achieve what your are looking for.


Update January 2016:

With Git 2.8 (Q1 2016), you will be able to fetch submodules in parallel (!) with git fetch --recurse-submodules -j2.
See "How to speed up / parallelize downloads of git submodules using git clone --recursive?"

apache mod_rewrite is not working or not enabled

On centOS7 I changed the file /etc/httpd/conf/httpd.conf

from AllowOverride None to AllowOverride All

Set Locale programmatically

simple and easy

Locale locale = new Locale("en", "US");
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = locale;
res.updateConfiguration(conf, dm);

where "en" is language code and "US" is country code.

Unsupported major.minor version 52.0

I ran into this issue in Eclipse on Mac OS X v10.9 (Mavericks). I tried many answers on Stack Overflow ... finally, after a full day I *installed a fresh version of the Android SDK (and updated Eclipse, menu Project ? Properties ? Android to use the new path)*.

I had to get SDK updates, but only pulling down those updates I thought were necessary, avoiding APIs I were not working with (like Wear and TV) .. and that did the trick. Apparently, it seems I had corrupted my SDK somewhere along the way.

BTW .. I did see the error re-surface with one project in my workspace, but it seemed related to an import of appcompat-7, which I was not using. After rm-ing that project, so far haven't seen the issue resurface.

Get the Last Inserted Id Using Laravel Eloquent

Here is how we can get last inserted id in Laravel 4

public function store()
{
    $input = Input::all();

    $validation = Validator::make($input, user::$rules);

    if ($validation->passes())
    {

     $user= $this->user->create(array(
            'name'              => Input::get('name'),
            'email'             => Input::get('email'),
            'password'          => Hash::make(Input::get('password')),
        ));
        $lastInsertedId= $user->id; //get last inserted record's user id value
        $userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
        $user->update($userId); //update newly created record by storing the value of last inserted id
            return Redirect::route('users.index');
        }
    return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
    }

How can I reference a commit in an issue comment on GitHub?

Answer above is missing an example which might not be obvious (it wasn't to me).

Url could be broken down into parts

https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
                  \_____/\________/       \_______________________________________/
                   |        |                              |
            Account name    |                      Hash of revision
                        Project name              

Hash can be found here (you can click it and will get the url from browser).

enter image description here

Hope this saves you some time.

Query error with ambiguous column name in SQL

if you join 2 or more tables and they have similar names for their columns sql server wants you to qualify columns which they belong.

SELECT  ev.[ID]
    ,[Description]
    FROM   [Events] as ev 
    LEFT JOIN  [Units] as un ON ev.UnitID = un.UnitId  

if Events and Units tables has same column name (ID) SQL server wants you to use aliases.

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

jQuery equivalent to Prototype array.last()

SugarJS

It's not jQuery but another library you may find useful in addition to jQuery: Try SugarJS.

Sugar is a Javascript library that extends native objects with helpful methods. It is designed to be intuitive, unobtrusive, and let you do more with less code.

With SugarJS, you can do:

[1,2,3,4].last()    //  => 4

That means, your example does work out of the box:

var array = [1,2,3,4];
var lastEl = array.last();    //  => 4

More Info

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I ran across this post today as I was running into the same issue and had the same problem of the javascript not running with the CDATA tags listed above. I corrected the CDATA tags to look like:

<script type="text/javascript">
//<![CDATA[ 

your javascript code here

//]]>
</script>

Then everything worked perfectly!

Target elements with multiple classes, within one rule

.border-blue.background { ... } is for one item with multiple classes.
.border-blue, .background { ... } is for multiple items each with their own class.
.border-blue .background { ... } is for one item where '.background' is the child of '.border-blue'.

See Chris' answer for a more thorough explanation.

Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

Could not find module FindOpenCV.cmake ( Error in configuration process)

  1. apt-get install libopencv-dev
  2. export OpenCV_DIR=/usr/share/OpenCV
  3. the header of cpp file should contain: #include #include "opencv2/highgui/highgui.hpp"

#include #include

not original cv.h

Syntax for a for loop in ruby

To iterate a loop a fixed number of times, try:

n.times do
  #Something to be done n times
end

Py_Initialize fails - unable to load the file system codec

I had the same issue and found this question. However from the answers here I was not able to solve my problem. I started debugging the cpython code and thought that I might be discovered a bug. Therefore I opened a issue on the python issue tracker.

My mistake was that I did not understand that Py_SetPath clears all inferred paths. So one needs to set all paths when calling this function.

For completion I also copied the most important part of the conversation below.


My original issue text

I compiled the source of CPython 3.7.3 myself on Windows with Visual Studio 2017 together with some packages like e.g numpy. When I start the Python Interpreter I am able to import and use numpy. However when I am running the same script via the C-API I get an ModuleNotFoundError.

So the first thing I did, was to check if numpy is in my site-packages directory and indeed there is a folder named numpy-1.16.2-py3.7-win-amd64.egg. (Makes sense because the python interpreter can find numpy)

The next thing I did was to get some information about the sys.path variable created when running the script via the C-API.

#### sys.path content ####
C:\Work\build\product\python37.zip
C:\Work\build\product\DLLs
C:\Work\build\product\lib
C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO\2017\PROFESSIONAL\COMMON7\IDE\EXTENSIONS\TESTPLATFORM
C:\Users\rvq\AppData\Roaming\Python\Python37\site-packages

Examining the content of sys.path I noticed two things.

  1. C:\Work\build\product\python37.zip has the correct path 'C:\Work\build\product\'. There was just no zip file. All my files and directory were unpacked. So I zipped the files to an archive named python37.zip and this resolved the import error.

  2. C:\Users\rvq\AppData\Roaming\Python\Python37\site-packages is wrong it should be C:\Work\build\product\Lib\site-packages but I dont know how this wrong path is created.

The next thing I tried was to use Py_SetPath(L"C:/Work/build/product/Lib/site-packages") before calling Py_Initialize(). This led to

Fatal Python Error 'unable to load the file system encoding' ModuleNotFoundError: No module named 'encodings'

I created a minimal c++ project with exact these two calls and started to debug Cpython.

int main()
{
  Py_SetPath(L"C:/Work/build/product/Lib/site-packages");
  Py_Initialize();
}

I tracked the call of Py_Initialize() down to the call of

static int
zipimport_zipimporter___init___impl(ZipImporter *self, PyObject *path)

inside of zipimport.c

The comment above this function states the following:

Create a new zipimporter instance. 'archivepath' must be a path-like object to a zipfile, or to a specific path inside a zipfile. For example, it can be '/tmp/myimport.zip', or '/tmp/myimport.zip/mydirectory', if mydirectory is a valid directory inside the archive. 'ZipImportError' is raised if 'archivepath' doesn't point to a valid Zip archive. The 'archive' attribute of the zipimporter object contains the name of the zipfile targeted.

So for me it seems that the C-API expects the path set with Py_SetPath to be a path to a zipfile. Is this expected behaviour or is it a bug? If it is not a bug is there a way to changes this so that it can also detect directories?

PS: The ModuleNotFoundError did not occur for me when using Python 3.5.2+, which was the version I used in my project before. I also checked if I had set any PYTHONHOME or PYTHONPATH environment variables but I did not see one of them on my system.


Answer

This is probably a documentation failure more than anything else. We're in the middle of redesigning initialization though, so it's good timing to contribute this feedback.

The short answer is that you need to make sure Python can find the Lib/encodings directory, typically by putting the standard library in sys.path. Py_SetPath clears all inferred paths, so you need to specify all the places Python should look. (The rules for where Python looks automatically are complicated and vary by platform, which is something I'm keen to fix.)

Paths that don't exist are okay, and that's the zip file. You can choose to put the stdlib into a zip, and it will be found automatically if you name it the default path, but you can also leave it unzipped and reference the directory.

A full walk through on embedding is more than I'm prepared to type on my phone. Hopefully that's enough to get you going for now.

Why is volatile needed in C?

Another use for volatile is signal handlers. If you have code like this:

int quit = 0;
while (!quit)
{
    /* very small loop which is completely visible to the compiler */
}

The compiler is allowed to notice the loop body does not touch the quit variable and convert the loop to a while (true) loop. Even if the quit variable is set on the signal handler for SIGINT and SIGTERM; the compiler has no way to know that.

However, if the quit variable is declared volatile, the compiler is forced to load it every time, because it can be modified elsewhere. This is exactly what you want in this situation.

Limiting the output of PHP's echo to 200 characters

In this code we define a method and then we can simply call it. we give it two parameters. first one is text and the second one should be count of characters that you wanna display.

function the_excerpt(string $text,int $length){
    if(strlen($text) > $length){$text = substr($text,0,$length);}
    return $text; 
}

Serializing list to JSON

If using Python 2.5, you may need to import simplejson:

try:
    import json
except ImportError:
    import simplejson as json

How can I export a GridView.DataSource to a datatable or dataset?

Ambu,

I was having the same issue as you, and this is the code I used to figure it out. Although, I don't use the footer row section for my purposes, I did include it in this code.

    DataTable dt = new DataTable();

    // add the columns to the datatable            
    if (GridView1.HeaderRow != null)
    {

        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            dt.Columns.Add(GridView1.HeaderRow.Cells[i].Text);
        }
    }

    //  add each of the data rows to the table
    foreach (GridViewRow row in GridView1.Rows)
    {
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < row.Cells.Count; i++)
        {
            dr[i] = row.Cells[i].Text.Replace("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

    //  add the footer row to the table
    if (GridView1.FooterRow != null)
    {
        DataRow dr;
        dr = dt.NewRow();

        for (int i = 0; i < GridView1.FooterRow.Cells.Count; i++)
        {
            dr[i] = GridView1.FooterRow.Cells[i].Text.Replace("&nbsp;","");
        }
        dt.Rows.Add(dr);
    }

How to force garbage collection in Java?

Using the Java™ Virtual Machine Tool Interface (JVM TI), the function

jvmtiError ForceGarbageCollection(jvmtiEnv* env)

will "Force the VM to perform a garbage collection." The JVM TI is part of the JavaTM Platform Debugger Architecture (JPDA).

android: how to use getApplication and getApplicationContext from non activity / service class

The getApplication() method is located in the Activity class, so whenever you want getApplication() in a non activity class you have to pass an Activity instance to the constructor of that non activity class.

assume that test is my non activity class:

Test test = new Test(this);

In that class i have created one constructor:

 public Class Test
 {
    public Activity activity;
    public Test (Activity act)
    {
         this.activity = act;
         // Now here you can get getApplication()
    }
 }

Understanding REST: Verbs, error codes, and authentication

REST Basics

REST have an uniform interface constraint, which states that the REST client must rely on standards instead of application specific details of the actual REST service, so the REST client won't break by minor changes, and it will probably be reusable.

So there is a contract between the REST client and the REST service. If you use HTTP as the underlying protocol, then the following standards are part of the contract:

  • HTTP 1.1
    • method definitions
    • status code definitions
    • cache control headers
    • accept and content-type headers
    • auth headers
  • IRI (utf8 URI)
  • body (pick one)
    • registered application specific MIME type, e.g. maze+xml
    • vendor specific MIME type, e.g. vnd.github+json
    • generic MIME type with
  • hyperlinks
    • what should contain them (pick one)
      • sending in link headers
      • sending in a hypermedia response, e.g. html, atom+xml, hal+json, ld+json&hydra, etc...
    • semantics
      • use IANA link relations and probably custom link relations
      • use an application specific RDF vocab

REST has a stateless constraint, which declares that the communication between the REST service and client must be stateless. This means that the REST service cannot maintain the client states, so you cannot have a server side session storage. You have to authenticate every single request. So for example HTTP basic auth (part of the HTTP standard) is okay, because it sends the username and password with every request.

To answer you questions

  1. Yes, it can be.

    Just to mention, the clients do not care about the IRI structure, they care about the semantics, because they follow links having link relations or linked data (RDF) attributes.

    The only thing important about the IRIs, that a single IRI must identify only a single resource. It is allowed to a single resource, like an user, to have many different IRIs.

    It is pretty simple why we use nice IRIs like /users/123/password; it is much easier to write the routing logic on the server when you understand the IRI simply by reading it.

  2. You have more verbs, like PUT, PATCH, OPTIONS, and even more, but you don't need more of them... Instead of adding new verbs you have to learn how to add new resources.

    activate_login -> PUT /login/active true deactivate_login -> PUT /login/active false change_password -> PUT /user/xy/password "newpass" add_credit -> POST /credit/raise {details: {}}

    (The login does not make sense from REST perspective, because of the stateless constraint.)

  3. Your users do not care about why the problem exist. They want to know only if there is success or error, and probably an error message which they can understand, for example: "Sorry, but we weren't able to save your post.", etc...

    The HTTP status headers are your standard headers. Everything else should be in the body I think. A single header is not enough to describe for example detailed multilingual error messages.

  4. The stateless constraint (along with the cache and layered system constraints) ensures that the service scales well. You surely don't wan't to maintain millions of sessions on the server, when you can do the same on the clients...

    The 3rd party client gets an access token if the user grants access to it using the main client. After that the 3rd party client sends the access token with every request. There are more complicated solutions, for example you can sign every single request, etc. For further details check the OAuth manual.

Related literature

Initialise a list to a specific length in Python

list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

CodeIgniter Disallowed Key Characters

I got this error when sending data from a rich text editor where I had included an ampersand. Replacing the ampersand with %26 - the URL encoding of ampersand - solved the problem. I also found that a jQuery ajax request configured like this magically solves the problem:

request = $.ajax({
        "url": url,
        type: "PUT",
        dataType: "json",
        data: json
    });

where the object json is, surprise, surprise, a JSON object containing a property with a value that contains an ampersand.