Programs & Examples On #Hibernate session

A main Java interface to Hibernate persistence service.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

Border for an Image view in Android?

Following is my simplest solution to this lengthy trouble.

<FrameLayout
    android:layout_width="112dp"
    android:layout_height="112dp"
    android:layout_marginLeft="16dp" <!-- May vary according to your needs -->
    android:layout_marginRight="16dp" <!-- May vary according to your needs -->
    android:layout_centerVertical="true">
    <!-- following imageView acts as the boarder which sitting in the background of our main container ImageView -->
    <ImageView
        android:layout_width="112dp"
        android:layout_height="112dp"
        android:background="#000"/>
    <!-- following imageView holds the image as the container to our image -->
    <!-- layout_margin defines the width of our boarder, here it's 1dp -->
    <ImageView
        android:layout_width="110dp"
        android:layout_height="110dp"
        android:layout_margin="1dp"
        android:id="@+id/itemImageThumbnailImgVw"
        android:src="@drawable/banana"
        android:background="#FFF"/> </FrameLayout>

In the following answer I've explained it well enough, please have a look at that too!

I hope this will be helpful to someone else out there!

SQL Inner join more than two tables

Here is a general SQL query syntax to join three or more table. This SQL query should work in all major relation database e.g. MySQL, Oracle, Microsoft SQLServer, Sybase and PostgreSQL :

SELECT t1.col, t3.col FROM table1 join table2 ON table1.primarykey = table2.foreignkey
                                  join table3 ON table2.primarykey = table3.foreignkey

We first join table 1 and table 2 which produce a temporary table with combined data from table1 and table2, which is then joined to table3. This formula can be extended for more than 3 tables to N tables, You just need to make sure that SQL query should have N-1 join statement in order to join N tables. like for joining two tables we require 1 join statement and for joining 3 tables we need 2 join statement.

Use formula in custom calculated field in Pivot Table

Pivot table Excel2007- average to exclude zeros

=sum(XX:XX)/count if(XX:XX, ">0")

Invoice USD

Qty Rate(count) Value (sum) 300 0.000 000.000 1000 0.385 385.000

Average Rate Count should Exclude 0.000 rate

What is the "-->" operator in C/C++?

It's

#include <stdio.h>

int main(void) {
  int x = 10;
  while (x-- > 0) { // x goes to 0
    printf("%d ", x);
  }
  return 0;
}

Just the space makes the things look funny, -- decrements and > compares.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

try this:

=(RIGHT(E9;3))+(MID(E9;7;2)*1000)+(MID(E9;5;2)*3600000)+(LEFT(E9;2)*216000000)

Maybe you need to change semi-colon by coma...

React "after render" code?

There is actually a lot simpler and cleaner version than using request animationframe or timeouts. Iam suprised no one brought it up: the vanilla-js onload handler. If you can, use component did mount, if not, simply bind a function on the onload hanlder of the jsx component. If you want the function to run every render, also execute it before returning you results in the render function. the code would look like this:

_x000D_
_x000D_
runAfterRender = () => _x000D_
{_x000D_
  const myElem = document.getElementById("myElem")_x000D_
  if(myElem)_x000D_
  {_x000D_
    //do important stuff_x000D_
  }_x000D_
}_x000D_
_x000D_
render()_x000D_
{_x000D_
  this.runAfterRender()_x000D_
  return (_x000D_
    <div_x000D_
      onLoad = {this.runAfterRender}_x000D_
    >_x000D_
      //more stuff_x000D_
    </div>_x000D_
  )_x000D_
}
_x000D_
_x000D_
_x000D_

}

How can strings be concatenated?

Use + for string concatenation as:

section = 'C_type'
new_section = 'Sec_' + section

How to split a string and assign it to variables

**In this function you can able to split the function by golang using array of strings**

func SplitCmdArguments(args []string) map[string]string {
    m := make(map[string]string)
    for _, v := range args {
        strs := strings.Split(v, "=")
        if len(strs) == 2 {
            m[strs[0]] = strs[1]
        } else {
            log.Println("not proper arguments", strs)
        }
    }
    return m
}

NotificationCenter issue on Swift 3

I think it has changed again.

For posting this works in Xcode 8.2.

NotificationCenter.default.post(Notification(name:.UIApplicationWillResignActive)

Software Design vs. Software Architecture

Architecture is more like integrating various functionalities of a System to achive one goal of the System as a whole, while design addresses each functional requirements.

For example, take example of MVVM, which is an architectural pattern. For notification functionality, MVVM uses observer Pattern, which in turn is a design pattern,

window.location.href and window.open () methods in JavaScript

window.location.href is not a method, it's a property that will tell you the current URL location of the browser. Changing the value of the property will redirect the page.

window.open() is a method that you can pass a URL to that you want to open in a new window. For example:

window.location.href example:

window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

window.open('http://www.google.com'); //This will open Google in a new window.

Additional Information:

window.open() can be passed additional parameters. See: window.open tutorial

Spring boot - configure EntityManager

With Spring Boot its not necessary to have any config file like persistence.xml. You can configure with annotations Just configure your DB config for JPA in the

application.properties

spring.datasource.driverClassName=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@DB...
spring.datasource.username=username
spring.datasource.password=pass

spring.jpa.database-platform=org.hibernate.dialect....
spring.jpa.show-sql=true

Then you can use CrudRepository provided by Spring where you have standard CRUD transaction methods. There you can also implement your own SQL's like JPQL.

@Transactional
public interface ObjectRepository extends CrudRepository<Object, Long> {
...
}

And if you still need to use the Entity Manager you can create another class.

public class ObjectRepositoryImpl implements ObjectCustomMethods{

    @PersistenceContext
    private EntityManager em;

}

This should be in your pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.5.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.3.11.Final</version>
    </dependency>
</dependencies>

How to send a JSON object over Request with Android?

public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
    JSONArray array;
    @Override
    protected JSONArray doInBackground(Void... params) {

        try {
            commonurl cu = new commonurl();
            String u = cu.geturl("tempshowusermain.php");
            URL url =new URL(u);
          //  URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setDoInput(true);
            httpURLConnection.connect();

            JSONObject jsonObject=new JSONObject();
            jsonObject.put("lid",lid);


            DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            outputStream.write(jsonObject.toString().getBytes("UTF-8"));

            int code = httpURLConnection.getResponseCode();
            if (code == 200) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));

                StringBuffer stringBuffer = new StringBuffer();
                String line;

                while ((line = bufferedReader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                object =  new JSONObject(stringBuffer.toString());
             //   array = new JSONArray(stringBuffer.toString());
                array = object.getJSONArray("response");

            }

        } catch (Exception e) {

            e.printStackTrace();
        }
        return array;


    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();



    }

    @Override
    protected void onPostExecute(JSONArray array) {
        super.onPostExecute(array);
        try {
            for (int x = 0; x < array.length(); x++) {

                object = array.getJSONObject(x);
                ComonUserView commUserView=new ComonUserView();//  commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
                //pidArray.add(jsonObject2.getString("pid").toString());

                commUserView.setLid(object.get("lid").toString());
                commUserView.setUname(object.get("uname").toString());
                commUserView.setAboutme(object.get("aboutme").toString());
                commUserView.setHeight(object.get("height").toString());
                commUserView.setAge(object.get("age").toString());
                commUserView.setWeight(object.get("weight").toString());
                commUserView.setBodytype(object.get("bodytype").toString());
                commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
                commUserView.setImagepath(object.get("imagepath").toString());
                commUserView.setDistance(object.get("distance").toString());
                commUserView.setLookingfor(object.get("lookingfor").toString());
                commUserView.setStatus(object.get("status").toString());

                cm.add(commUserView);
            }
            custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
          gridusername.setAdapter(custuserprof);
            //  listusername.setAdapter(custuserprof);
            } catch (Exception e) {

                e.printStackTrace();
        }
    }

How do I drop table variables in SQL-Server? Should I even do this?

But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.

jQuery textbox change event doesn't fire until textbox loses focus?

if you write anything in your textbox, the event gets fired.
code as follows :

HTML:

<input type="text" id="textbox" />

JS:

<script type="text/javascript">
  $(function () {
      $("#textbox").bind('input', function() {
      alert("letter entered");
      });
   });
</script>

Difference between _self, _top, and _parent in the anchor tag target attribute

While these answers are good, IMHO I don't think they fully address the question.

The target attribute in an anchor tag tells the browser the target of the destination of the anchor. They were initially created in order to manipulate and direct anchors to the frame system of document. This was well before CSS came to the aid of HTML developers.

While target="_self" is default by browser and the most common target is target="_blank" which opens the anchor in a new window(which has been redirected to tabs by browser settings usually). The "_parent", "_top" and framename tags are left a mystery to those that aren't familiar with the days of iframe site building as the trend.

target="_self" This opens an anchor in the same frame. What is confusing is that because we generally don't write in frames anymore (and the frame and frameset tags are obsolete in HTML5) people assume this a same window function. Instead if this anchor was nested in frames it would open in a sandbox mode of sorts, meaning only in that frame.

target="_parent" Will open the in the next level up of a frame if they were nested to inside one another

target="_top" This breaks outside of all the frames it is nested in and opens the link as top document in the browser window.

target="framename This was originally deprecated but brought back in HTML5. This will target the exact frame in question. While the name was the proper method that method has been replaced with using the id identifying tag.

<!--Example:-->

<html>
<head>
</head>
<body>
<iframe src="url1" name="A"><p> This my first iframe</p></iframe>
<iframe src="url2" name="B"><p> This my second iframe</p></iframe>
<iframe src="url3" name="C"><p> This my third iframe</p></iframe>

<a href="url4" target="B"></a>
</body>
</html>

Currently running queries in SQL Server

Depending on your privileges, this query might work:

SELECT sqltext.TEXT,
req.session_id,
req.status,
req.command,
req.cpu_time,
req.total_elapsed_time
FROM sys.dm_exec_requests req
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext

Ref: http://blog.sqlauthority.com/2009/01/07/sql-server-find-currently-running-query-t-sql

How to get the last character of a string in a shell?

For anyone interested in a pure POSIX method:

https://github.com/spiralofhope/shell-random/blob/master/live/sh/scripts/string-fetch-last-character.sh

#!/usr/bin/env  sh

string_fetch_last_character() {
  length_of_string=${#string}
  last_character="$string"
  i=1
  until [ $i -eq "$length_of_string" ]; do
    last_character="${last_character#?}"
    i=$(( i + 1 ))
  done

  printf  '%s'  "$last_character"
}


string_fetch_last_character  "$string"

How to split elements of a list?

Something like:

>>> l = ['element1\t0238.94', 'element2\t2.3904', 'element3\t0139847']
>>> [i.split('\t', 1)[0] for i in l]
['element1', 'element2', 'element3']

Download TS files from video stream

I needed to download HLS video and audio streams from a e-learning portal with session-protected content with application/mp2t MIME content type.

Manually copying all authentication headers into the downloading scripts would be too cumbersome.

But the task got much easier with help of Video DownloadHelper Firefox extension and it's Companion App. It allowed to download both m3u8 playlists with TS chunks lists and actual video and audio streams into mp4 files via a click of button while correctly preserving authentication headers.

The resulting separate video and audio files can be merged with ffmpeg:

ffmpeg -i video.mp4 -i audio.mp4 -acodec copy -vcodec copy video-and-audio.mp4 

or with mp4box:

mp4box -add audio.mp4#audio video.mp4 -out video-and-audio.mp4

Tried Video DownloadHelper Chrome extension too, but it didn't work for me.

Using async/await for multiple tasks

I just want to add to all great answers above, that if you write a library it's a good practice to use ConfigureAwait(false) and get better performance, as said here.

So this snippet seems to be better:

 public static async Task DoWork() 
 {
     int[] ids = new[] { 1, 2, 3, 4, 5 };
     await Task.WhenAll(ids.Select(i => DoSomething(1, i))).ConfigureAwait(false);
 }

A full fiddle link here.

What's the "Content-Length" field in HTTP header?

rfc2616

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

It doesn't matter what the content-type is.

Extension at post below.

Linux command: How to 'find' only text files?

Although it is an old question, I think this info bellow will add to the quality of the answers here.

When ignoring files with the executable bit set, I just use this command:

find . ! -perm -111

To keep it from recursively enter into other directories:

find . -maxdepth 1 ! -perm -111

No need for pipes to mix lots of commands, just the powerful plain find command.

  • Disclaimer: it is not exactly what OP asked, because it doesn't check if the file is binary or not. It will, for example, filter out bash script files, that are text themselves but have the executable bit set.

That said, I hope this is useful to anyone.

Should a function have only one return statement?

This is mainly a hang over from Fortran, where it was possible to pass multiple statement labels to a function so it could return to any one of them.

So this sort of code was perfectly valid

       CALL SOMESUB(ARG1, 101, 102, 103)
C Some code
 101   CONTINUE
C Some more code
 102   CONTINUE
C Yet more code
 103   CONTINUE
C You get the general idea

But the function being called made the decision as to where your code path went. Efficient? Probably. Maintainable? No.

That is where that rule comes from (incidentally along with no multiple entry points to a function, which is possible in fortran and assembler, but not in C).

However, the wording of that looks like it can be applied to other languages (the one about multiple entry points can't be applied to other languages, so it's not really a program). So the rule got carried over, even though it refers to a completely different problem, and isn't applicable.

For more structured languages, that rule needs to be dropped or at least thought through more. Certainly a function spattered with returns is difficult to understand, but returning at the beginning isn't an issue. And in some C++ compilers a single return point may generate better code if you're returning a value from only one place.

But the original rule is misunderstood, misapplied. and no longer relevant.

iOS application: how to clear notifications?

If you're coming here wondering the opposite (as I was), this post may be for you.

I couldn't figure out why my notifications were clearing when I cleared the badge...I manually increment the badge and then want to clear it when the user enters the app. That's no reason to clear out the notification center, though; they may still want to see or act on those notifications.

Negative 1 does the trick, luckily:

[UIApplication sharedApplication].applicationIconBadgeNumber = -1;

How do you count the elements of an array in java

You can declare an array of booleans with the same length of your array:

true: is used
false: is not used

and change the value of the same cell number to true. Then you can count how many cells are used by using a for loop.

How can I output UTF-8 from Perl?

do in your shell: $ env |grep LANG

This will probably show that your shell is not using a utf-8 locale.

PHP, getting variable from another php-file

You could also use file_get_contents

 $url_a="http://127.0.0.1/get_value.php?line=a&shift=1&tgl=2017-01-01";
 $data_a=file_get_contents($url_a);

 echo $data_a;

Multi-line strings in PHP

Maybe try ".=" indead of "="?

$xml="l";
$xml.="vv";

will give you "lvv";

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

Python For loop get index

Use the enumerate() function to generate the index along with the elements of the sequence you are looping over:

for index, w in enumerate(loopme):
    print "CURRENT WORD IS", w, "AT CHARACTER", index 

In bootstrap how to add borders to rows without adding up?

You can simply use the border class from bootstrap:

<div class="row border border-dark">
...
</div>

For more details visit the following link: Borders

Weird behavior of the != XPath operator

If $AccountNumber or $Balance is a node-set, then this behavior could easily happen. It's not because and is being treated as or.

For example, if $AccountNumber referred to nodes with the values 12345 and 66 and $Balance referred to nodes with the values 55 and 0, then $AccountNumber != '12345' would be true (because 66 is not equal to 12345) and $Balance != '0' would be true (because 55 is not equal to 0).

I'd suggest trying this instead:

<xsl:when test="not($AccountNumber = '12345' or $Balance = '0')">

$AccountNumber = '12345' or $Balance = '0' will be true any time there is an $AccountNumber with the value 12345 or there is a $Balance with the value 0, and if you apply not() to that, you will get a false result.

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);

"Prevent saving changes that require the table to be re-created" negative effects

SQL Server drops and recreates the tables only if you:

  • Add a new column
  • Change the Allow Nulls setting for a column
  • Change the column order in the table
  • Change the column data type

Using ALTER is safer, as in case the metadata is lost while you re-create the table, your data will be lost.

Run as java application option disabled in eclipse

I had this same problem. For me, the reason turned out to be that I had a mismatch in the name of the class and the name of the file. I declared class "GenSig" in a file called "SignatureTester.java".

I changed the name of the class to "SignatureTester", and the "Run as Java Application" option showed up immediately.

Add element to a JSON file?

alternatively you can do

iter(data).next()['f'] = var

SQLAlchemy ORDER BY DESCENDING?

from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))

Usage from @jpmc26

Unit tests vs Functional tests

very simply we can say:

  • black box: user interface test like functional test
  • white box: code test like unit test

read more here.

What is __init__.py for?

In Python the definition of package is very simple. Like Java the hierarchical structure and the directory structure are the same. But you have to have __init__.py in a package. I will explain the __init__.py file with the example below:

package_x/
|--  __init__.py
|--    subPackage_a/
|------  __init__.py
|------  module_m1.py
|--    subPackage_b/
|------  __init__.py
|------  module_n1.py
|------  module_n2.py
|------  module_n3.py

__init__.py can be empty, as long as it exists. It indicates that the directory should be regarded as a package. Of course, __init__.py can also set the appropriate content.

If we add a function in module_n1:

def function_X():
    print "function_X in module_n1"
    return

After running:

>>>from package_x.subPackage_b.module_n1 import function_X
>>>function_X()

function_X in module_n1 

Then we followed the hierarchy package and called module_n1 the function. We can use __init__.py in subPackage_b like this:

__all__ = ['module_n2', 'module_n3']

After running:

>>>from package_x.subPackage_b import * 
>>>module_n1.function_X()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named module_n1

Hence using * importing, module package is subject to __init__.py content.

Can Mysql Split a column?

Use

substring_index(`column`,',',1) ==> first value
substring_index(substring_index(`column`,',',-2),',',1)=> second value
substring_index(substring_index(`column`,',',-1),',',1)=> third value

in your where clause.

SELECT * FROM `table`
WHERE 
substring_index(`column`,',',1)<0 
AND
substring_index(`column`,',',1)>5

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

If you are using Any CPU, you might encounter this issue if the Prefer 32-bit option is checked:

Make sure you uncheck this option in the project's property's Build tab!

enter image description here

Eclipse : Failed to connect to remote VM. Connection refused.

I faced the same issue. But i resolved it by changing my port numbers to different one.

How do SO_REUSEADDR and SO_REUSEPORT differ?

Mecki's answer is absolutly perfect, but it's worth adding that FreeBSD also supports SO_REUSEPORT_LB, which mimics Linux' SO_REUSEPORT behaviour - it balances the load; see setsockopt(2)

How to pass a type as a method parameter in Java

If you want to pass the type, than the equivalent in Java would be

java.lang.Class

If you want to use a weakly typed method, then you would simply use

java.lang.Object

and the corresponding operator

instanceof

e.g.

private void foo(Object o) {

  if(o instanceof String) {

  }

}//foo

However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.

The real question is what you actually want to achieve here, otherwise it is difficult to answer:

Or is there a better way?

Comparing two arrays of objects, and exclude the elements who match values into new array in JS

Just using the Array iteration methods built into JS is fine for this:

_x000D_
_x000D_
var result1 = [_x000D_
    {id:1, name:'Sandra', type:'user', username:'sandra'},_x000D_
    {id:2, name:'John', type:'admin', username:'johnny2'},_x000D_
    {id:3, name:'Peter', type:'user', username:'pete'},_x000D_
    {id:4, name:'Bobby', type:'user', username:'be_bob'}_x000D_
];_x000D_
_x000D_
var result2 = [_x000D_
    {id:2, name:'John', email:'[email protected]'},_x000D_
    {id:4, name:'Bobby', email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var props = ['id', 'name'];_x000D_
_x000D_
var result = result1.filter(function(o1){_x000D_
    // filter out (!) items in result2_x000D_
    return !result2.some(function(o2){_x000D_
        return o1.id === o2.id;          // assumes unique id_x000D_
    });_x000D_
}).map(function(o){_x000D_
    // use reduce to make objects with only the required properties_x000D_
    // and map to apply this to the filtered array as a whole_x000D_
    return props.reduce(function(newo, name){_x000D_
        newo[name] = o[name];_x000D_
        return newo;_x000D_
    }, {});_x000D_
});_x000D_
_x000D_
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) +_x000D_
        '</pre>';
_x000D_
_x000D_
_x000D_

If you are doing this a lot, then by all means look at external libraries to help you out, but it's worth learning the basics first, and the basics will serve you well here.

ORA-12560: TNS:protocol adaptor error

Add to the enviroment vars the following varibale and value to identify the place of the tnsnames.ora file:

TNS_ADMIN

C:\oracle\product\10.2.0\client_1\network\admin

How to set radio button selected value using jquery

for multiple dropdowns

$('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked");

here RBLExperienceApplicable is the matching part of the radio button groups input tag ids. and [id^=RBLExperienceApplicable] matches all the radio button whose id start with RBLExperienceApplicable

Xcode 10, Command CodeSign failed with a nonzero exit code

For me I had to go to keychain, select the "login" keychain, double click on the iOS Developer:myname key, click the access control tab and switch the radio button to Allow all applications to access this item.

How can I get a uitableViewCell by indexPath?

Swift

let indexpath = IndexPath(row: 0, section: 0)
if let cell = tableView.cellForRow(at: indexPath) as? <UITableViewCell or CustomCell> {
    cell.backgroundColor = UIColor.red
}

get name of a variable or parameter

What you are passing to GETNAME is the value of myInput, not the definition of myInput itself. The only way to do that is with a lambda expression, for example:

var nameofVar = GETNAME(() => myInput);

and indeed there are examples of that available. However! This reeks of doing something very wrong. I would propose you rethink why you need this. It is almost certainly not a good way of doing it, and forces various overheads (the capture class instance, and the expression tree). Also, it impacts the compiler: without this the compiler might actually have chosen to remove that variable completely (just using the stack without a formal local).

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

TL;DR;

Use let...of instead of let...in !!


If you're new to Angular (>2.x) and possibly migrating from Angular1.x, most likely you're confusing in with of. As andreas has mentioned in the comments below for ... of iterates over values of an object while for ... in iterates over properties in an object. This is a new feature introduced in ES2015.

Simply replace:

<!-- Iterate over properties (incorrect in our case here) -->
<div *ngFor="let talk in talks">

with

<!-- Iterate over values (correct way to use here) -->
<div *ngFor="let talk of talks">

So, you must replace in with of inside ngFor directive to get the values.

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

Assuming those methods are in one of the libs it looks like an ordering problem.

When linking libraries into an executable they are done in the order they are declared.
Also the linker will only take the methods/functions required to resolve currently outstanding dependencies. If a subsequent library then uses methods/functions that were not originally required by the objects you will have missing dependencies.

How it works:

  • Take all the object files and combine them into an executable
  • Resolve any dependencies among object files.
  • For-each library in order:
    • Check unresolved dependencies and see if the lib resolves them.
    • If so load required part into the executable.

Example:

Objects requires:

  • Open
  • Close
  • BatchRead
  • BatchWrite

Lib 1 provides:

  • Open
  • Close
  • read
  • write

Lib 2 provides

  • BatchRead (but uses lib1:read)
  • BatchWrite (but uses lib1:write)

If linked like this:

gcc -o plop plop.o -l1 -l2

Then the linker will fail to resolve the read and write symbols.

But if I link the application like this:

gcc -o plop plop.o -l2 -l1

Then it will link correctly. As l2 resolves the BatchRead and BatchWrite dependencies but also adds two new ones (read and write). When we link with l1 next all four dependencies are resolved.

autocomplete ='off' is not working when the input type is password and make the input field above it to enable autocomplete

I've found that if the input has no name (e.g. the name attribute is not set), the browser can't autocomplete the field. I know this is not a solution for everyone, but if you submit your form through AJAX, you may try this.

How do I put variable values into a text string in MATLAB?

I just realized why I was having so much trouble - in MATLAB you can't store strings of different lengths as an array using square brackets. Using square brackets concatenates strings of varying lengths into a single character array.

    >> a=['matlab','is','fun']

a =

matlabisfun

>> size(a)

ans =

     1    11

In a character array, each character in a string counts as one element, which explains why the size of a is 1X11.

To store strings of varying lengths as elements of an array, you need to use curly braces to save as a cell array. In cell arrays, each string is treated as a separate element, regardless of length.

>> a={'matlab','is','fun'}

a = 

    'matlab'    'is'    'fun'

>> size(a)

ans =

     1     3

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Recently, I explored the possibilities to parameterize the folder to scan through and the place where the result of recursive scan will be stored. At the end, I also did summarize the number of folders scanned and number of files inside as well. Sharing it with community in case it may help other developers.

    ##Script Starts
    #read folder to scan and file location to be placed

    $whichFolder = Read-Host -Prompt 'Which folder to Scan?'  
    $whereToPlaceReport = Read-Host -Prompt 'Where to place Report'
    $totalFolders = 1
    $totalFiles = 0

    Write-Host "Process started..."

    #IMP separator ? : used as a file in window cannot contain this special character in the file name

    #Get Foldernames into Variable for ForEach Loop
    $DFSFolders = get-childitem -path $whichFolder | where-object {$_.Psiscontainer -eq "True"} |select-object name ,fullName

    #Below Logic for Main Folder
    $mainFiles = get-childitem -path "C:\Users\User\Desktop" -file
    ("Folder Path" + "?" + "Folder Name" + "?" + "File Name " + "?"+ "File Length" )| out-file "$whereToPlaceReport\Report.csv" -Append

    #Loop through folders in main Directory
    foreach($file in $mainFiles)
    {

    $totalFiles = $totalFiles + 1
    ("C:\Users\User\Desktop" + "?" + "Main Folder" + "?"+ $file.name + "?" + $file.length ) | out-file "$whereToPlaceReport\Report.csv" -Append
    }


    foreach ($DFSfolder in $DFSfolders)
    {
    #write the folder name in begining
    $totalFolders = $totalFolders + 1

    write-host " Reading folder C:\Users\User\Desktop\$($DFSfolder.name)"
    #$DFSfolder.fullName | out-file "C:\Users\User\Desktop\PoC powershell\ok2.csv" -Append
    #For Each Folder obtain objects in a specified directory, recurse then filter for .sft file type, obtain the filename, then group, sort and eventually show the file name and total incidences of it.

    $files = get-childitem -path "$whichFolder\$($DFSfolder.name)" -recurse

    foreach($file in $files)
    {
    $totalFiles = $totalFiles + 1
    ($DFSfolder.fullName + "?" + $DFSfolder.name + "?"+ $file.name + "?" + $file.length ) | out-file "$whereToPlaceReport\Report.csv" -Append
    }

    }


    # If running in the console, wait for input before closing.
    if ($Host.Name -eq "ConsoleHost")
    {

    Write-Host "" 
    Write-Host ""
    Write-Host ""

    Write-Host  "                            **Summary**"  -ForegroundColor Red
    Write-Host  "                            ------------" -ForegroundColor Red

    Write-Host  "                           Total Folders Scanned = $totalFolders "  -ForegroundColor Green
    Write-Host  "                           Total Files   Scanned = $totalFiles "     -ForegroundColor Green

    Write-Host "" 
    Write-Host "" 
        Write-Host "I have done my Job,Press any key to exit" -ForegroundColor white
        $Host.UI.RawUI.FlushInputBuffer()   # Make sure buffered input doesn't "press a key" and skip the ReadKey().
        $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
    }

##Output

enter image description here

##Bat Code to run above powershell command

@ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%MyPowerShellScript.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";

How to implement a Keyword Search in MySQL?

Personally, I wouldn't use the LIKE string comparison on the ID field or any other numeric field. It doesn't make sense for a search for ID# "216" to return 16216, 21651, 3216087, 5321668..., and so on and so forth; likewise with salary.

Also, if you want to use prepared statements to prevent SQL injections, you would use a query string like:

SELECT * FROM job WHERE `position` LIKE CONCAT('%', ? ,'%') OR ...

How to merge 2 JSON objects from 2 files using jq?

First, {"value": .value} can be abbreviated to just {value}.

Second, the --argfile option (available in jq 1.4 and jq 1.5) may be of interest as it avoids having to use the --slurp option.

Putting these together, the two objects in the two files can be combined in the specified way as follows:

$ jq -n --argfile o1 file1 --argfile o2 file2 '$o1 * $o2 | {value}'

The '-n' flag tells jq not to read from stdin, since inputs are coming from the --argfile options here.

Note on --argfile

The jq manual deprecates --argfile because its semantics are non-trivial: if the specified input file contains exactly one JSON entity, then that entity is read as is; otherwise, the items in the stream are wrapped in an array.

If you are uncomfortable using --argfile, there are several alternatives you may wish to consider. In doing so, be assured that using --slurpfile does not incur the inefficiencies of the -s command-line option when the latter is used with multiple files.

sh: react-scripts: command not found after running npm start

You shoundt use neither SPACES neither some Special Caracters in you path, like for example using "&". I my case I was using this path: "D:\P&D\mern" and because of this "&" I lost 50 minutes trying to solve the problem! :/

Living and Learning!

How to make for loops in Java increase by increments other than 1

Simply try this

for(int i=0; i<5; i=i+2){//value increased by 2
//body
}

OR

for(int i=0; i<5; i+=2){//value increased by 2
//body
}

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

ActivityCompat.requestPermissions not showing dialog box

For me the issue was I had an invalid request code. I choose 0xDEADBEEF as a request code and it was silently failing (maybe it's cast to something smaller than 32-bit somewhere internally?) If I choose 255 everything worked fine as NightSkyDev described above.

How to prevent http file caching in Apache httpd (MAMP)

Tried this? Should work in both .htaccess, httpd.conf and in a VirtualHost (usually placed in httpd-vhosts.conf if you have included it from your httpd.conf)

<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>

100% Prevent Files from being cached

This is similar to how google ads employ the header Cache-Control: private, x-gzip-ok="" > to prevent caching of ads by proxies and clients.

From http://www.askapache.com/htaccess/using-http-headers-with-htaccess.html

And optionally add the extension for the template files you are retrieving if you are using an extension other than .html for those.

runOnUiThread in fragment

In Xamarin.Android

For Fragment:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

For Activity:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

Happy coding :-)

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

Here are three different checkmark styles you can use:

_x000D_
_x000D_
ul:first-child  li:before { content:"\2713\0020"; }  /* OR */_x000D_
ul:nth-child(2) li:before { content:"\2714\0020"; }  /* OR */_x000D_
ul:last-child   li:before { content:"\2611\0020"; }_x000D_
ul { list-style-type: none; }
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul><!-- not working on Stack snippet; check fiddle demo -->_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jsFiddle

References:

getting the ng-object selected with ng-change

If Divyesh Rupawala's answer doesn't work (passing the current item as the parameter), then please see the onChanged() function in this Plunker. It's using this:

http://plnkr.co/edit/B5TDQJ

Error when trying vagrant up

Check the following entry in your Vagrantfile

Every Vagrant development environment requires a box.
You can search for boxes at https://vagrantcloud.com/search.
  config.vm.box = "base"

This is the default file setting which is created with vagrant init command. But what you need to do is do initialise vagrant environment with an OS box. For instance $vagrant init centos/7. And the Vagrantfile will look something like this:

Every Vagrant development environment requires a box.
You can search for boxes at https://vagrantcloud.com/search.
  config.vm.box = "centos/7"

This will resolve the error of not found base when doing a vagrant up.

How to force maven update?

I tried all the answers here but nothing seemed to work. Restarted my computer first then ran mvn clean install -U. That solved my problem.

UPDATE if exists else INSERT in SQL Server 2008

Many people will suggest you use MERGE, but I caution you against it. By default, it doesn't protect you from concurrency and race conditions any more than multiple statements, but it does introduce other dangers:

http://www.mssqltips.com/sqlservertip/3074/use-caution-with-sql-servers-merge-statement/

Even with this "simpler" syntax available, I still prefer this approach (error handling omitted for brevity):

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
UPDATE dbo.table SET ... WHERE PK = @PK;
IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(PK, ...) SELECT @PK, ...;
END
COMMIT TRANSACTION;

A lot of folks will suggest this way:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
IF EXISTS (SELECT 1 FROM dbo.table WHERE PK = @PK)
BEGIN
  UPDATE ...
END
ELSE
BEGIN
  INSERT ...
END
COMMIT TRANSACTION;

But all this accomplishes is ensuring you may need to read the table twice to locate the row(s) to be updated. In the first sample, you will only ever need to locate the row(s) once. (In both cases, if no rows are found from the initial read, an insert occurs.)

Others will suggest this way:

BEGIN TRY
  INSERT ...
END TRY
BEGIN CATCH
  IF ERROR_NUMBER() = 2627
    UPDATE ...
END CATCH

However, this is problematic if for no other reason than letting SQL Server catch exceptions that you could have prevented in the first place is much more expensive, except in the rare scenario where almost every insert fails. I prove as much here:

Not sure what you think you gain by having a single statement; I don't think you gain anything. MERGE is a single statement but it still has to really perform multiple operations anyway - even though it makes you think it doesn't.

ASP.NET 4.5 has not been registered on the Web server

I had the same problem. After a long search , I change the application pool to ASP.NET v4.x in the IIS manager.

What does Visual Studio mean by normalize inconsistent line endings?

What that usually means is that you have lines ending with something other than a carriage return/line feed pair. It often happens when you copy and paste from a web page into the code editor.

Normalizing the line endings is just making sure that all of the line ending characters are consistent. It prevents one line from ending in \r\n and another ending with \r or \n; the first is the Windows line end pair, while the others are typically used for Mac or Linux files.

Since you're developing in Visual Studio, you'll obviously want to choose "Windows" from the drop down. :-)

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For C++, you could do:

export CXXFLAGS=-m32

This works with cmake.

How can I generate an ObjectId with mongoose?

I needed to generate mongodb ids on client side.

After digging into the mongodb source code i found they generate ObjectIDs using npm bson lib.

If ever you need only to generate an ObjectID without installing the whole mongodb / mongoose package, you can import the lighter bson library :

const bson = require('bson');
new bson.ObjectId(); // 5cabe64dcf0d4447fa60f5e2

Note: There is also an npm project named bson-objectid being even lighter

base64 encode in MySQL

Looks like no, though it was requested, and there’s a UDF for it.

Edit: Or there’s… this. Ugh.

How to limit google autocomplete results to City and Country only

Also you will need to zoom and center the map due to your country restrictions!

Just use zoom and center parameters! ;)

function initialize() {
  var myOptions = {
    zoom: countries['us'].zoom,
    center: countries['us'].center,
    mapTypeControl: false,
    panControl: false,
    zoomControl: false,
    streetViewControl: false
  };

  ... all other code ...

}

How to printf long long

%lld is the standard C99 way, but that doesn't work on the compiler that I'm using (mingw32-gcc v4.6.0). The way to do it on this compiler is: %I64d

So try this:

if(e%n==0)printf("%15I64d -> %1.16I64d\n",e, 4*pi);

and

scanf("%I64d", &n);

The only way I know of for doing this in a completely portable way is to use the defines in <inttypes.h>.

In your case, it would look like this:

scanf("%"SCNd64"", &n);
//...    
if(e%n==0)printf("%15"PRId64" -> %1.16"PRId64"\n",e, 4*pi);

It really is very ugly... but at least it is portable.

Getting the computer name in Java

I'm not so thrilled about the InetAddress.getLocalHost().getHostName() solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:

  1. What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.

  2. What if the host is not connected to any network and has no network interfaces ?

All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME on all versions of Windows and the environment variable HOSTNAME on Unix/Linux/MacOS (or alternatively the output from host command hostname if the HOSTNAME environment variable is not available as is the case in old shells like Bourne and Korn).

I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName() method. But that's just me.

UPDATE (Unices)

As others have pointed out the HOSTNAME environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?

Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec() to capture the output from the hostname command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).

Long read

I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName() solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.

It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.

Understanding __getitem__ method

The magic method __getitem__ is basically used for accessing list items, dictionary entries, array elements etc. It is very useful for a quick lookup of instance attributes.

Here I am showing this with an example class Person that can be instantiated by 'name', 'age', and 'dob' (date of birth). The __getitem__ method is written in a way that one can access the indexed instance attributes, such as first or last name, day, month or year of the dob, etc.

import copy

# Constants that can be used to index date of birth's Date-Month-Year
D = 0; M = 1; Y = -1

class Person(object):
    def __init__(self, name, age, dob):
        self.name = name
        self.age = age
        self.dob = dob

    def __getitem__(self, indx):
        print ("Calling __getitem__")
        p = copy.copy(self)

        p.name = p.name.split(" ")[indx]
        p.dob = p.dob[indx] # or, p.dob = p.dob.__getitem__(indx)
        return p

Suppose one user input is as follows:

p = Person(name = 'Jonab Gutu', age = 20, dob=(1, 1, 1999))

With the help of __getitem__ method, the user can access the indexed attributes. e.g.,

print p[0].name # print first (or last) name
print p[Y].dob  # print (Date or Month or ) Year of the 'date of birth'

changing minDate option in JQuery DatePicker not working

Say we have two date select fields, field1, and field2. field2 date depends on field1

$('#field2').datepicker();
$('#field1').datepicker({
  onSelect: function(dateText, inst) {
    $('#field2').val("");
    $('#field2').datepicker("option", "minDate", new Date(dateText));
  }
});

How to know function return type and argument types?

This is how dynamic languages work. It is not always a good thing though, especially if the documentation is poor - anyone tried to use a poorly documented python framework? Sometimes you have to revert to reading the source.

Here are some strategies to avoid problems with duck typing:

  • create a language for your problem domain
  • this will help you to name stuff properly
  • use types to represent concepts in your domain language
  • name function parameters using the domain language vocabulary

Also, one of the most important points:

  • keep data as local as possible!

There should only be a few well-defined and documented types being passed around. Anything else should be obvious by looking at the code: Don't have weird parameter types coming from far away that you can't figure out by looking in the vicinity of the code...

Related, (and also related to docstrings), there is a technique in python called doctests. Use that to document how your methods are expected to be used - and have nice unit test coverage at the same time!

T-SQL: Looping through an array of known values

What I do in this scenario is create a table variable to hold the Ids.

  Declare @Ids Table (id integer primary Key not null)
  Insert @Ids(id) values (4),(7),(12),(22),(19)

-- (or call another table valued function to generate this table)

Then loop based on the rows in this table

  Declare @Id Integer
  While exists (Select * From @Ids)
    Begin
      Select @Id = Min(id) from @Ids
      exec p_MyInnerProcedure @Id 
      Delete from @Ids Where id = @Id
    End

or...

  Declare @Id Integer = 0 -- assuming all Ids are > 0
  While exists (Select * From @Ids
                where id > @Id)
    Begin
      Select @Id = Min(id) 
      from @Ids Where id > @Id
      exec p_MyInnerProcedure @Id 
    End

Either of above approaches is much faster than a cursor (declared against regular User Table(s)). Table-valued variables have a bad rep because when used improperly, (for very wide tables with large number of rows) they are not performant. But if you are using them only to hold a key value or a 4 byte integer, with a index (as in this case) they are extremely fast.

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

There is now a new way of addressing this issue - if you remove position: relative from the container which needs to have the overflow-y visible, you can have overflow-y visible and overflow-x hidden, and vice versa (have overflow-x visible and overflow-y hidden, just make sure the container with the visible property is not relatively positioned).

See this post from CSS Tricks for more details - it worked for me: https://css-tricks.com/popping-hidden-overflow/

How to create a zip file in Java

Single file:

String filePath = "/absolute/path/file1.txt";
String zipPath = "/absolute/path/output.zip";

try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) {
    File fileToZip = new File(filePath);
    zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
    Files.copy(fileToZip.toPath(), zipOut);
}

Multiple files:

List<String> filePaths = Arrays.asList("/absolute/path/file1.txt", "/absolute/path/file2.txt");
String zipPath = "/absolute/path/output.zip";

try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipPath))) {
    for (String filePath : filePaths) {
        File fileToZip = new File(filePath);
        zipOut.putNextEntry(new ZipEntry(fileToZip.getName()));
        Files.copy(fileToZip.toPath(), zipOut);
    }
}

SQL update statement in C#

This is not a correct method of updating record in SQL:

command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";

You should write it like this:

command.CommandText = "UPDATE Student 
SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add";

Then you add the parameters same as you added them for the insert operation.

How to declare std::unique_ptr and what is the use of it?

The constructor of unique_ptr<T> accepts a raw pointer to an object of type T (so, it accepts a T*).

In the first example:

unique_ptr<int> uptr (new int(3));

The pointer is the result of a new expression, while in the second example:

unique_ptr<double> uptr2 (pd);

The pointer is stored in the pd variable.

Conceptually, nothing changes (you are constructing a unique_ptr from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:

unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);

Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).

This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:

unique_ptr<int> p = make_unique<int>(42);

Which is both clearer and safer. Now concerning this doubt of yours:

What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.

Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.

This way you do not have to remember doing delete on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:

{
    unique_ptr<int> p = make_unique<int>(42);
    // Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete

Now unique_ptr is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr is non-copyable.

As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.

Can an html element have multiple ids?

I'd like to say technically yes, since really what gets rendered is technically always browser dependent. Most browsers try to keep to the specifications as best they can and as far as I know there is nothing in the css specifications against it. I'm only going to vouch for the actual html,css,javascript code that gets sent to the browser before any other interpretter steps in.

However I also say no since every browser I typically test on doesn't actually let you. If you need to see for yourself save the following as a .html file and open it up in the major browsers. In all browsers I tested on the javascript function will not match to an element. However, remove either "hunkojunk" from the id tag and all works fine. Sample Code

<html>
<head>
</head>
<body>
    <p id="hunkojunk1 hunkojunk2"></p>

<script type="text/javascript">
    document.getElementById('hunkojunk2').innerHTML = "JUNK JUNK JUNK JUNK JUNK JUNK";
</script>
</body>
</html>

Replace the single quote (') character from a string

You can escape the apostrophe with a \ character as well:

mystring.replace('\'', '')

What is the point of "Initial Catalog" in a SQL Server connection string?

Setting an Initial Catalog allows you to set the database that queries run on that connection will use by default. If you do not set this for a connection to a server in which multiple databases are present, in many cases you will be required to have a USE statement in every query in order to explicitly declare which database you are trying to run the query on. The Initial Catalog setting is a good way of explicitly declaring a default database.

java.io.FileNotFoundException: /storage/emulated/0/New file.txt: open failed: EACCES (Permission denied)

For SDK 29 :

String str1 = "";
folder1 = new File(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
if (folder1.exists()) {str1 = folder1.toString() + File.separator;}

public static void createTextFile(String sBody, String FileName, String Where) {
    try {
        File gpxfile = new File(Where, FileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then you can save your file like this :

createTextFile("This is Content","file.txt",str1);

JavaScript "cannot read property "bar" of undefined

Just check for it before you pass to your function. So you would pass:

thing.foo ? thing.foo.bar : undefined

Xcopy Command excluding files and folders

Just give full path to exclusion file: eg..

-- no - - - - -xcopy c:\t1 c:\t2 /EXCLUDE:list-of-excluded-files.txt

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\list-of-excluded-files.txt

In this example the file would be located " C:\list-of-excluded-files.txt "

or...

correct - - - xcopy c:\t1 c:\t2 /EXCLUDE:C:\mybatch\list-of-excluded-files.txt

In this example the file would be located " C:\mybatch\list-of-excluded-files.txt "

Full path fixes syntax error.

How to monitor the memory usage of Node.js?

Also, if you'd like to know global memory rather than node process':

var os = require('os');

os.freemem();
os.totalmem();

See documentation

Bootstrap 3 breakpoints and media queries

I know this is a bit old, but i thought i would contribute. Basing myself on the answer by @Sophy, this is what I did to add a .xxs breakpoint. I have not taken care of visible-inline, table.visible, etc classes.

/*==========  Mobile First Method  ==========*/

  .col-xxs-12, .col-xxs-11, .col-xxs-10, .col-xxs-9, .col-xxs-8, .col-xxs-7, .col-xxs-6, .col-xxs-5, .col-xxs-4, .col-xxs-3, .col-xxs-2, .col-xxs-1 {
    position: relative;
    min-height: 1px;
    padding-left: 15px;
    padding-right: 15px;
    float: left;
  }

.visible-xxs {
  display:none !important;
}

/* Custom, iPhone Retina */
@media only screen and (min-width : 320px) and (max-width:479px) {

  .visible-xxs {
    display: block !important;
  }
  .visible-xs {
    display:none !important;
  }

  .hidden-xs {
    display:block !important;
  }

  .hidden-xxs {
    display:none !important;
  }

  .col-xxs-12 {
    width: 100%;
  }
  .col-xxs-11 {
    width: 91.66666667%;
  }
  .col-xxs-10 {
    width: 83.33333333%;
  }
  .col-xxs-9 {
    width: 75%;
  }
  .col-xxs-8 {
    width: 66.66666667%;
  }
  .col-xxs-7 {
    width: 58.33333333%;
  }
  .col-xxs-6 {
    width: 50%;
  }
  .col-xxs-5 {
    width: 41.66666667%;
  }
  .col-xxs-4 {
    width: 33.33333333%;
  }
  .col-xxs-3 {
    width: 25%;
  }
  .col-xxs-2 {
    width: 16.66666667%;
  }
  .col-xxs-1 {
    width: 8.33333333%;
  }
  .col-xxs-pull-12 {
    right: 100%;
  }
  .col-xxs-pull-11 {
    right: 91.66666667%;
  }
  .col-xxs-pull-10 {
    right: 83.33333333%;
  }
  .col-xxs-pull-9 {
    right: 75%;
  }
  .col-xxs-pull-8 {
    right: 66.66666667%;
  }
  .col-xxs-pull-7 {
    right: 58.33333333%;
  }
  .col-xxs-pull-6 {
    right: 50%;
  }
  .col-xxs-pull-5 {
    right: 41.66666667%;
  }
  .col-xxs-pull-4 {
    right: 33.33333333%;
  }
  .col-xxs-pull-3 {
    right: 25%;
  }
  .col-xxs-pull-2 {
    right: 16.66666667%;
  }
  .col-xxs-pull-1 {
    right: 8.33333333%;
  }
  .col-xxs-pull-0 {
    right: auto;
  }
  .col-xxs-push-12 {
    left: 100%;
  }
  .col-xxs-push-11 {
    left: 91.66666667%;
  }
  .col-xxs-push-10 {
    left: 83.33333333%;
  }
  .col-xxs-push-9 {
    left: 75%;
  }
  .col-xxs-push-8 {
    left: 66.66666667%;
  }
  .col-xxs-push-7 {
    left: 58.33333333%;
  }
  .col-xxs-push-6 {
    left: 50%;
  }
  .col-xxs-push-5 {
    left: 41.66666667%;
  }
  .col-xxs-push-4 {
    left: 33.33333333%;
  }
  .col-xxs-push-3 {
    left: 25%;
  }
  .col-xxs-push-2 {
    left: 16.66666667%;
  }
  .col-xxs-push-1 {
    left: 8.33333333%;
  }
  .col-xxs-push-0 {
    left: auto;
  }
  .col-xxs-offset-12 {
    margin-left: 100%;
  }
  .col-xxs-offset-11 {
    margin-left: 91.66666667%;
  }
  .col-xxs-offset-10 {
    margin-left: 83.33333333%;
  }
  .col-xxs-offset-9 {
    margin-left: 75%;
  }
  .col-xxs-offset-8 {
    margin-left: 66.66666667%;
  }
  .col-xxs-offset-7 {
    margin-left: 58.33333333%;
  }
  .col-xxs-offset-6 {
    margin-left: 50%;
  }
  .col-xxs-offset-5 {
    margin-left: 41.66666667%;
  }
  .col-xxs-offset-4 {
    margin-left: 33.33333333%;
  }
  .col-xxs-offset-3 {
    margin-left: 25%;
  }
  .col-xxs-offset-2 {
    margin-left: 16.66666667%;
  }
  .col-xxs-offset-1 {
    margin-left: 8.33333333%;
  }
  .col-xxs-offset-0 {
    margin-left: 0%;
  }

}

/* Extra Small Devices, Phones */
@media only screen and (min-width : 480px) {

  .visible-xs {
    display:block !important;
  }

}

/* Small Devices, Tablets */
@media only screen and (min-width : 768px) {

  .visible-xs {
    display:none !important;
  }

}

/* Medium Devices, Desktops */
@media only screen and (min-width : 992px) {

}

/* Large Devices, Wide Screens */
@media only screen and (min-width : 1200px) {

}

Context.startForegroundService() did not then call Service.startForeground()

Problem With Android O API 26

If you stop the service right away (so your service does not actually really runs (wording / comprehension) and you are way under the ANR interval, you still need to call startForeground before stopSelf

https://plus.google.com/116630648530850689477/posts/L2rn4T6SAJ5

Tried this Approach But it Still creates an error:-

if (Util.SDK_INT > 26) {
    mContext.startForegroundService(playIntent);
} else {
    mContext.startService(playIntent);
}

I Am Using this until the Error is Resolved

mContext.startService(playIntent);

Return anonymous type results?

Try this to get dynamic data. You can convert code for List<>

public object GetDogsWithBreedNames()
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                 join b in db.Breeds on d.BreedId equals b.BreedId
                 select new
                        {
                            Name = d.Name,
                            BreedName = b.BreedName
                        };
    return result.FirstOrDefault();
}

dynamic dogInfo=GetDogsWithBreedNames();
var name = dogInfo.GetType().GetProperty("Name").GetValue(dogInfo, null);
var breedName = dogInfo.GetType().GetProperty("BreedName").GetValue(dogInfo, null);

How to give a pattern for new line in grep?

just found

grep $'\r'

It's using $'\r' for c-style escape in Bash.

in this article

How do you manually execute SQL commands in Ruby On Rails using NuoDB

The working command I'm using to execute custom SQL statements is:

results = ActiveRecord::Base.connection.execute("foo")

with "foo" being the sql statement( i.e. "SELECT * FROM table").

This command will return a set of values as a hash and put them into the results variable.

So on my rails application_controller.rb I added this:

def execute_statement(sql)
  results = ActiveRecord::Base.connection.execute(sql)

  if results.present?
    return results
  else
    return nil
  end
end

Using execute_statement will return the records found and if there is none, it will return nil.

This way I can just call it anywhere on the rails application like for example:

records = execute_statement("select * from table")

"execute_statement" can also call NuoDB procedures, functions, and also Database Views.

How do I center a Bootstrap div with a 'spanX' class?

Update

As of BS3 there's a .center-block helper class. From the docs:

// Classes
.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

// Usage as mixins
.element {
  .center-block();
}

There is hidden complexity in this seemingly simple problem. All the answers given have some issues.

1. Create a Custom Class (Major Gotcha)

Create .col-centred class, but there is a major gotcha.

.col-centred {
   float: none !important;
   margin: 0 auto;
}

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
  Centred content.
</div>

The Gotcha

Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.

The Fixes

You can resolve this issue by using a clearfix element. Using z-index to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.

<div class="row">
  <div class="col-lg-12">
    I get overlapped by `col-lg-7 centered` unless there's a clearfix.
  </div>
  <div class="clearfix"></div>
  <div class="col-lg-7 centred">
  </div>
</div>

Or you can isolate the centred column in its own row.

<div class="row">
  <div class="col-lg-12">
  </div>
</div>
<div class="row">
  <div class="col-lg-7 centred">
    Look I am in my own row.
  </div>
</div>

2. Use col-lg-offset-x or spanx-offset (Major Gotcha)

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
  Centred content.
</div>

The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).

Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.

3. Create an Inner Centred Column

This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.

.col-centred {
   margin: 0 auto;
}

<div class="row">
  <div class="col-lg-12">
    <div class="centred">
        Look I am in my own row.
    </div>
  </div>
</div>

.war vs .ear file

From GeekInterview:

In J2EE application, modules are packaged as EAR, JAR, and WAR based on their functionality

JAR: EJB modules which contain enterprise java beans (class files) and EJB deployment descriptor are packed as JAR files with .jar extension

WAR: Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as a JAR file with .war (web archive) extension

EAR: All the above files (.jar and .war) are packaged as a JAR file with .ear (enterprise archive) extension and deployed into Application Server.

Difference between malloc and calloc?

A difference not yet mentioned: size limit

void *malloc(size_t size) can only allocate up to SIZE_MAX.

void *calloc(size_t nmemb, size_t size); can allocate up about SIZE_MAX*SIZE_MAX.

This ability is not often used in many platforms with linear addressing. Such systems limit calloc() with nmemb * size <= SIZE_MAX.

Consider a type of 512 bytes called disk_sector and code wants to use lots of sectors. Here, code can only use up to SIZE_MAX/sizeof disk_sector sectors.

size_t count = SIZE_MAX/sizeof disk_sector;
disk_sector *p = malloc(count * sizeof *p);

Consider the following which allows an even larger allocation.

size_t count = something_in_the_range(SIZE_MAX/sizeof disk_sector + 1, SIZE_MAX)
disk_sector *p = calloc(count, sizeof *p);

Now if such a system can supply such a large allocation is another matter. Most today will not. Yet it has occurred for many years when SIZE_MAX was 65535. Given Moore's law, suspect this will be occurring about 2030 with certain memory models with SIZE_MAX == 4294967295 and memory pools in the 100 of GBytes.

How do I check whether a file exists without exceptions?

Use the following code:

def findfile(self, filepath)
  flag = false
  for filename in os.listdir(filepath)
    if filename == "your file name"
      flag = true
      break
    else 
      print("no file found")
  if(flag == true)
    return true
  else 
    return false

Getting number of elements in an iterator in Python

A quick benchmark:

import collections
import itertools

def count_iter_items(iterable):
    counter = itertools.count()
    collections.deque(itertools.izip(iterable, counter), maxlen=0)
    return next(counter)

def count_lencheck(iterable):
    if hasattr(iterable, '__len__'):
        return len(iterable)

    d = collections.deque(enumerate(iterable, 1), maxlen=1)
    return d[0][0] if d else 0

def count_sum(iterable):           
    return sum(1 for _ in iterable)

iter = lambda y: (x for x in xrange(y))

%timeit count_iter_items(iter(1000))
%timeit count_lencheck(iter(1000))
%timeit count_sum(iter(1000))

The results:

10000 loops, best of 3: 37.2 µs per loop
10000 loops, best of 3: 47.6 µs per loop
10000 loops, best of 3: 61 µs per loop

I.e. the simple count_iter_items is the way to go.

Adjusting this for python3:

61.9 µs ± 275 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
74.4 µs ± 190 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
82.6 µs ± 164 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Getting text from td cells with jQuery

$(".field-group_name").each(function() {
        console.log($(this).text());
    });

How do I unbind "hover" in jQuery?

unbind() doesn't work with hardcoded inline events.

So, for example, if you want to unbind the mouseover event from <div id="some_div" onmouseover="do_something();">, I found that $('#some_div').attr('onmouseover','') is a quick and dirty way to achieve it.

How to display my application's errors in JSF?

JSF is a beast. I may be missing something, but I used to solve similar problems by saving the desired message to a property of the bean, and then displaying the property via an outputText:

<h:outputText
    value="#{CreateNewPasswordBean.errorMessage}"
    render="#{CreateNewPasswordBean.errorMessage != null}" />

Decorators with parameters?

This is a template for a function decorator that does not require () if no parameters are to be given:

import functools


def decorator(x_or_func=None, *decorator_args, **decorator_kws):
    def _decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kws):
            if 'x_or_func' not in locals() \
                    or callable(x_or_func) \
                    or x_or_func is None:
                x = ...  # <-- default `x` value
            else:
                x = x_or_func
            return func(*args, **kws)

        return wrapper

    return _decorator(x_or_func) if callable(x_or_func) else _decorator

an example of this is given below:

def multiplying(factor_or_func=None):
    def _decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            if 'factor_or_func' not in locals() \
                    or callable(factor_or_func) \
                    or factor_or_func is None:
                factor = 1
            else:
                factor = factor_or_func
            return factor * func(*args, **kwargs)
        return wrapper
    return _decorator(factor_or_func) if callable(factor_or_func) else _decorator


@multiplying
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying()
def summing(x): return sum(x)

print(summing(range(10)))
# 45


@multiplying(10)
def summing(x): return sum(x)

print(summing(range(10)))
# 450

how to read a long multiline string line by line in python

by splitting with newlines.

for line in wallop_of_a_string_with_many_lines.split('\n'):
  #do_something..

if you iterate over a string, you are iterating char by char in that string, not by line.

>>>string = 'abc'
>>>for line in string:
    print line

a
b
c

Pandas DataFrame concat vs append

Pandas concat vs append vs join vs merge

  • Concat gives the flexibility to join based on the axis( all rows or all columns)

  • Append is the specific case(axis=0, join='outer') of concat

  • Join is based on the indexes (set by set_index) on how variable =['left','right','inner','couter']

  • Merge is based on any particular column each of the two dataframes, this columns are variables on like 'left_on', 'right_on', 'on'

twitter bootstrap text-center when in xs mode

There is nothing built into bootstrap for this, but some simple css could fix it. Something like this should work. Not tested though

 @media (max-width: 768px) {
      .col-xs-12.text-right, .col-xs-12.text-left {
              text-align: center;
       } 
    }

How to reload .bash_profile from the command line?

Simply type source ~/.bash_profile

Alternatively, if you like saving keystrokes you can type . ~/.bash_profile

Getting the first and last day of a month, using a given DateTime object

Try this one:

string strDate = DateTime.Now.ToString("MM/01/yyyy");

How can I trim beginning and ending double quotes from a string?

Kotlin

In Kotlin you can use String.removeSurrounding(delimiter: CharSequence)

E.g.

string.removeSurrounding("\"")

Removes the given delimiter string from both the start and the end of this string if and only if it starts with and ends with the delimiter. Otherwise returns this string unchanged.

The source code looks like this:

public fun String.removeSurrounding(delimiter: CharSequence): String = removeSurrounding(delimiter, delimiter)

public fun String.removeSurrounding(prefix: CharSequence, suffix: CharSequence): String {
    if ((length >= prefix.length + suffix.length) && startsWith(prefix) && endsWith(suffix)) {
        return substring(prefix.length, length - suffix.length)
    }
    return this
}

Setting Java heap space under Maven 2 on Windows

On windows:

Add an environmental variable (in both system and user's variables, I have some weird problem, that it gets the var from various places, so I add them in both of them).

Name it MAVEN_OPTS.

Value will be: -Xms1024m -Xmx3000m -XX:MaxPermSize=1024m -XX:+CMSClassUnloadingEnabled

The numbers can be different, make them relative to your mem size.

I had that problem and this fixed it, nothing else!

How to set a default row for a query that returns no rows?

I figured it out, and it should also work for other systems too. It's a variation of WW's answer.

select rate 
from d_payment_index
where fy = 2007
  and payment_year = 2008
  and program_id = 18
union
select 0 as rate 
from d_payment_index 
where not exists( select rate 
                  from d_payment_index
                  where fy = 2007
                    and payment_year = 2008
                    and program_id = 18 )

How to install and run Typescript locally in npm?

tsc requires a config file or .ts(x) files to compile.

To solve both of your issues, create a file called tsconfig.json with the following contents:

{
    "compilerOptions": {
        "outFile": "../../built/local/tsc.js"
    },
    "exclude": [
        "node_modules"
    ]
}

Also, modify your npm run with this

tsc --config /path/to/a/tsconfig.json

What is LD_LIBRARY_PATH and how to use it?

LD_LIBRARY_PATH is the predefined environmental variable in Linux/Unix which sets the path which the linker should look in to while linking dynamic libraries/shared libraries.

LD_LIBRARY_PATH contains a colon separated list of paths and the linker gives priority to these paths over the standard library paths /lib and /usr/lib. The standard paths will still be searched, but only after the list of paths in LD_LIBRARY_PATH has been exhausted.

The best way to use LD_LIBRARY_PATH is to set it on the command line or script immediately before executing the program. This way the new LD_LIBRARY_PATH isolated from the rest of your system.

Example Usage:

$ export LD_LIBRARY_PATH="/list/of/library/paths:/another/path"
$ ./program

Since you talk about .dll you are on a windows system and a .dll must be placed at a path which the linker searches at link time, in windows this path is set by the environmental variable PATH, So add that .dll to PATH and it should work fine.

How to get data out of a Node.js http get request

Simple Working Example of Http request using node.

const http = require('https')

httprequest().then((data) => {
        const response = {
            statusCode: 200,
            body: JSON.stringify(data),
        };
    return response;
});
function httprequest() {
     return new Promise((resolve, reject) => {
        const options = {
            host: 'jsonplaceholder.typicode.com',
            path: '/todos',
            port: 443,
            method: 'GET'
        };
        const req = http.request(options, (res) => {
          if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        req.on('error', (e) => {
          reject(e.message);
        });
        // send the request
       req.end();
    });
}

How do you POST to a page using the PHP header() function?

In addition to what Salaryman said, take a look at the classes in PEAR, there are HTTP request classes there that you can use even if you do not have the cURL extension installed in your PHP distribution.

long long in C/C++

It depends in what mode you are compiling. long long is not part of the C++ standard but only (usually) supported as extension. This affects the type of literals. Decimal integer literals without any suffix are always of type int if int is big enough to represent the number, long otherwise. If the number is even too big for long the result is implementation-defined (probably just a number of type long int that has been truncated for backward compatibility). In this case you have to explicitly use the LL suffix to enable the long long extension (on most compilers).

The next C++ version will officially support long long in a way that you won't need any suffix unless you explicitly want the force the literal's type to be at least long long. If the number cannot be represented in long the compiler will automatically try to use long long even without LL suffix. I believe this is the behaviour of C99 as well.

How do I extend a class with c# extension methods?

I would do the same as Kumu

namespace ExtensionMethods
{
    public static class MyExtensionMethods
    {
        public static DateTime Tomorrow(this DateTime date)
        {
           return date.AddDays(1);
        }    
    }
}

but call it like this new DateTime().Tomorrow();

Think it makes more seens than DateTime.Now.Tomorrow();

Jenkins Git Plugin: How to build specific tag?

In a latest Jenkins (1.639 and above) you can:

  1. just specify name of tag in a field 'Branches to build'.
  2. in a parametrized build you can use parameter as variable in a same field 'Branches to build' i.e. ${Branch_to_build}.
  3. you can install Git Parameter Plugin which will provide to you functionality by listing of all available branches and tags.

How to change Named Range Scope

here's how I promote all worksheet names to global names. YMMV

For Each wsh In ActiveWorkbook.Worksheets
For Each n In wsh.Names
    ' Get unqualified range name
    Dim s As String
    s = Split(n.Name, "!")(UBound(Split(n.Name, "!")))
    ' Add to "Workbook" scope
    n.RefersToRange.Name = s
    ' Remove from "Worksheet" scope
    Call n.Delete
Next n
Next wsh

Sql Query to list all views in an SQL Server 2005 database

To finish the set off (with what has already been suggested):

SELECT * FROM sys.views

This gives extra properties on each view, not available from sys.objects (which contains properties common to all types of object) or INFORMATION_SCHEMA.VIEWS. Though INFORMATION_SCHEMA approach does provide the view definition out-of-the-box.

Converting Java objects to JSON with Jackson

To convert your object in JSON with Jackson:

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);

Which maven dependencies to include for spring 3.0?

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.0.RELEASE</version>
</dependency>

Batch file include external file for variables

Kinda old subject but I had same question a few days ago and I came up with another idea (maybe someone will still find it usefull)

For example you can make a config.bat with different subjects (family, size, color, animals) and apply them individually in any order anywhere you want in your batch scripts:

@echo off
rem Empty the variable to be ready for label config_all
set config_all_selected=

rem Go to the label with the parameter you selected
goto :config_%1

REM This next line is just to go to end of file 
REM in case that the parameter %1 is not set
goto :end

REM next label is to jump here and get all variables to be set
:config_all
set config_all_selected=1


:config_family
set mother=Mary
set father=John
set sister=Anna
rem This next line is to skip going to end if config_all label was selected as parameter
if not "%config_all_selected%"=="1" goto :end

:config_test
set "test_parameter_all=2nd set: The 'all' parameter WAS used before this echo"
if not "%config_all_selected%"=="1" goto :end

:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end


:config_color
set first_color=blue
set second_color=green
if not "%config_all_selected%"=="1" goto :end


:config_animals
set dog=Max
set cat=Miau
if not "%config_all_selected%"=="1" goto :end


:end

After that, you can use it anywhere by calling fully with 'call config.bat all' or calling only parts of it (see example bellow) The idea in here is that sometimes is more handy when you have the option not to call everything at once. Some variables maybe you don't want to be called yet so you can call them later.

Example test.bat

@echo off

rem This is added just to test the all parameter
set "test_parameter_all=1st set: The 'all' parameter was NOT used before this echo"

call config.bat size

echo My birthday present had a width of %width% and a height of %height%

call config.bat family
call config.bat animals

echo Yesterday %father% and %mother% surprised %sister% with a cat named %cat%
echo Her brother wanted the dog %dog%

rem This shows you if the 'all' parameter was or not used (just for testing)
echo %test_parameter_all%

call config.bat color

echo His lucky color is %first_color% even if %second_color% is also nice.

echo.
pause

Hope it helps the way others help me in here with their answers.

A short version of the above:

config.bat

@echo off
set config_all_selected=
goto :config_%1
goto :end

:config_all
set config_all_selected=1

:config_family
set mother=Mary
set father=John
set daughter=Anna
if not "%config_all_selected%"=="1" goto :end

:config_size
set width=20
set height=40
if not "%config_all_selected%"=="1" goto :end

:end

test.bat

@echo off

call config.bat size
echo My birthday present had a width of %width% and a height of %height%

call config.bat family
echo %father% and %mother% have a daughter named %daughter%

echo.
pause

Good day.

How to print the data in byte array as characters?

If you want to print the bytes as chars you can use the String constructor.

byte[] bytes = new byte[] { -1, -128, 1, 127 };
System.out.println(new String(bytes, 0));

How to keep an iPhone app running on background fully operational

Depends what it does. If your app takes up too much memory, or makes calls to functions/classes it shouldn't, SpringBoard may terminate it. However, it will most likely be rejected by Apple, as it does not follow their 7 background uses.

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in

The in operator only works on objects. You are using it on a string. Make sure your value is an object before you using $.each. In this specific case, you have to parse the JSON:

$.each(JSON.parse(myData), ...);

how to stop a for loop

Try to simply use break statement.

Also you can use the following code as an example:

a = [[0,1,0], [1,0,0], [1,1,1]]
b = [[0,0,0], [0,0,0], [0,0,0]]

def check_matr(matr, expVal):    
    for row in matr:
        if len(set(row)) > 1 or set(row).pop() != expVal:
            print 'Wrong'
            break# or return
        else:
            print 'ok'
    else:
        print 'empty'
check_matr(a, 0)
check_matr(b, 0)

How to play video with AVPlayerViewController (AVKit) in Swift

Objective c

This only works in Xcode 7

Go to .h file and import AVKit/AVKit.h and AVFoundation/AVFoundation.h. Then go .m file and add this code:

NSURL *url=[[NSBundle mainBundle]URLForResource:@"arreg" withExtension:@"mp4"];
AVPlayer *video=[AVPlayer playerWithURL:url];
AVPlayerViewController *controller=[[AVPlayerViewController alloc]init];
controller.player=video;
[self.view addSubview:controller.view];
controller.view.frame=self.view.frame;
[self addChildViewController:controller];
[video play];

ExecuteNonQuery doesn't return results

Because the SET NOCOUNT option is set to on. Remove the line "SET NOCOUNT ON;" in your query or stored procedure.

See more at SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete.

Understanding string reversal via slicing

we can use append and pop to do it

def rev(s):
    i = list(s)
    o = list()
    while len(i) > 0:
        o.append(t.pop())

    return ''.join(o)

javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found

I use this class and have no problem.

public class WCFs
{
    // https://192.168.30.8/myservice.svc?wsdl
    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String URL = "192.168.30.8";
    private static final String SERVICE = "/myservice.svc?wsdl";
    private static String SOAP_ACTION = "http://tempuri.org/iWCFserviceMe/";


    public static Thread myMethod(Runnable rp)
    {
        String METHOD_NAME = "myMethod";

        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        request.addProperty("Message", "Https WCF Running...");
        return _call(rp,METHOD_NAME, request);
    }

    protected static HandlerThread _call(final RunProcess rp,final String METHOD_NAME, SoapObject soapReq)
    {
        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        int TimeOut = 5*1000;

        envelope.dotNet = true;
        envelope.bodyOut = soapReq;
        envelope.setOutputSoapObject(soapReq);

        final HttpsTransportSE httpTransport_net = new HttpsTransportSE(URL, 443, SERVICE, TimeOut);

        try
        {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() // use this section if crt file is handmake
            {
                @Override
                public boolean verify(String hostname, SSLSession session)
                {
                    return true;
                }
            });

            KeyStore k = getFromRaw(R.raw.key, "PKCS12", "password");
            ((HttpsServiceConnectionSE) httpTransport_net.getServiceConnection()).setSSLSocketFactory(getSSLSocketFactory(k, "SSL"));


        }
        catch(Exception e){}

        HandlerThread thread = new HandlerThread("wcfTd"+ Generator.getRandomNumber())
        {
            @Override
            public void run()
            {
                Handler h = new Handler(Looper.getMainLooper());
                Object response = null;

                for(int i=0; i<4; i++)
                {
                    response = send(envelope, httpTransport_net , METHOD_NAME, null);

                    try
                    {if(Thread.currentThread().isInterrupted()) return;}catch(Exception e){}

                    if(response != null)
                        break;

                    ThreadHelper.threadSleep(250);
                }

                if(response != null)
                {
                    if(rp != null)
                    {
                        rp.setArguments(response.toString());
                        h.post(rp);
                    }
                }
                else
                {
                    if(Thread.currentThread().isInterrupted())
                        return;

                    if(rp != null)
                    {
                        rp.setExceptionState(true);
                        h.post(rp);
                    }
                }

                ThreadHelper.stopThread(this);
            }
        };

        thread.start();

        return thread;
    }


    private static Object send(SoapSerializationEnvelope envelope, HttpTransportSE androidHttpTransport, String METHOD_NAME, List<HeaderProperty> headerList)
    {
        try
        {
            if(headerList != null)
                androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope, headerList);
            else
                androidHttpTransport.call(SOAP_ACTION + METHOD_NAME, envelope);

            Object res = envelope.getResponse();

            if(res instanceof SoapPrimitive)
                return (SoapPrimitive) envelope.getResponse();
            else if(res instanceof SoapObject)
                return ((SoapObject) envelope.getResponse());
        }
        catch(Exception e)
        {}

        return null;
    }

    public static KeyStore getFromRaw(@RawRes int id, String algorithm, String filePassword)
    {
        try
        {
            InputStream inputStream = ResourceMaster.openRaw(id);
            KeyStore keystore = KeyStore.getInstance(algorithm);
            keystore.load(inputStream, filePassword.toCharArray());
            inputStream.close();

            return keystore;
        }
        catch(Exception e)
        {}

        return null;
    }

    public static SSLSocketFactory getSSLSocketFactory(KeyStore trustKey, String SSLAlgorithm)
    {
        try
        {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(trustKey);

            SSLContext context = SSLContext.getInstance(SSLAlgorithm);//"SSL" "TLS"
            context.init(null, tmf.getTrustManagers(), null);

            return context.getSocketFactory();
        }
        catch(Exception e){}

        return null;
    }
}

Assigning default value while creating migration file

Default migration generator does not handle default values (column modifiers are supported but do not include default or null), but you could create your own generator.

You can also manually update the migration file prior to running rake db:migrate by adding the options to add_column:

add_column :tweet, :retweets_count, :integer, :null => false, :default => 0

... and read Rails API

ERROR Android emulator gets killed

I have been struggling with the The emulator process for AVD Pixel_2_API_30 was killed for a while now. I was trying to launch a Pixel 2 API 30 running android 11.0, I tried all the possible solutions but nothing seemed to work. I decided t use a different setup e.g. Pixel 2 API 28 running android 9.0, and it worked perfectly. I am not sure what causes the bug in the higher-level API or android version though... So my suggestion is to change the API and android version IF all of the other solutions didn't work.

How to completely uninstall Android Studio on Mac?

Run the following commands in the terminal:

rm -Rf /Applications/Android\ Studio.app  
rm -Rf ~/Library/Preferences/AndroidStudio*  
rm -Rf ~/Library/Preferences/com.google.android.*  
rm -Rf ~/Library/Preferences/com.android.*  
rm -Rf ~/Library/Application\ Support/AndroidStudio*  
rm -Rf ~/Library/Logs/AndroidStudio*  
rm -Rf ~/Library/Caches/AndroidStudio*  
rm -Rf ~/.AndroidStudio*  
rm -Rf ~/.gradle  
rm -Rf ~/.android  
rm -Rf ~/Library/Android*  
rm -Rf /usr/local/var/lib/android-sdk/  

To delete all projects:

rm -Rf ~/AndroidStudioProjects  

RegEx: How can I match all numbers greater than 49?

I know there is already a good answer posted, but it won't allow leading zeros. And I don't have enough reputation to leave a comment, so... Here's my solution allowing leading zeros:

First I match the numbers 50 through 99 (with possible leading zeros):

0*[5-9]\d

Then match numbers of 100 and above (also with leading zeros):

0*[1-9]\d{2,}

Add them together with an "or" and wrap it up to match the whole sentence:

^0*([1-9]\d{2,}|[5-9]\d)$

That's it!

Difference between `npm start` & `node app.js`, when starting app?

The documentation has been updated. My answer has substantial changes vs the accepted answer: I wanted to reflect documentation is up-to-date, and accepted answer has a few broken links.

Also, I didn't understand when the accepted answer said "it defaults to node server.js". I think the documentation clarifies the default behavior:

npm-start

Start a package

Synopsis

npm start [-- <args>]

Description

This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

In summary, running npm start could do one of two things:

  1. npm start {command_name}: Run an arbitrary command (i.e. if such command is specified in the start property of package.json's scripts object)
  2. npm start: Else if no start property exists (or no command_name is passed): Run node server.js, (which may not be appropriate, for example the OP doesn't have server.js; the OP runs nodeapp.js )
  3. I said I would list only 2 items, but are other possibilities (i.e. error cases). For example, if there is no package.json in the directory where you run npm start, you may see an error: npm ERR! enoent ENOENT: no such file or directory, open '.\package.json'

Windows command for file size only

Use a function to get rid off some limitation in the ~z operator. It is especially useful with a for loop:

@echo off
set size=0
call :filesize "C:\backup\20120714-0035\error.log"
echo file size is %size%
goto :eof

:: Set filesize of first argument in %size% variable, and return
:filesize
  set size=%~z1
  exit /b 0

Ping a site in Python?

It's hard to say what your question is, but there are some alternatives.

If you mean to literally execute a request using the ICMP ping protocol, you can get an ICMP library and execute the ping request directly. Google "Python ICMP" to find things like this icmplib. You might want to look at scapy, also.

This will be much faster than using os.system("ping " + ip ).

If you mean to generically "ping" a box to see if it's up, you can use the echo protocol on port 7.

For echo, you use the socket library to open the IP address and port 7. You write something on that port, send a carriage return ("\r\n") and then read the reply.

If you mean to "ping" a web site to see if the site is running, you have to use the http protocol on port 80.

For or properly checking a web server, you use urllib2 to open a specific URL. (/index.html is always popular) and read the response.

There are still more potential meaning of "ping" including "traceroute" and "finger".

Setting up and using environment variables in IntelliJ Idea

In addition to the above answer and restarting the IDE didn't do, try restarting "Jetbrains Toolbox" if you use it, this did it for me

Android marshmallow request permission?

I have used this wrapper (Recommended) written by google developers. Its super easy to use.

https://github.com/googlesamples/easypermissions

Function dealing with checking and ask for permission if required

public void locationAndContactsTask() {
    String[] perms = { Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_CONTACTS };
    if (EasyPermissions.hasPermissions(this, perms)) {
        // Have permissions, do the thing!
        Toast.makeText(this, "TODO: Location and Contacts things", Toast.LENGTH_LONG).show();
    } else {
        // Ask for both permissions
        EasyPermissions.requestPermissions(this, getString(R.string.rationale_location_contacts),
                RC_LOCATION_CONTACTS_PERM, perms);
    }
}

Happy coding :)

How to center the text in PHPExcel merged cell

if you want to align only this cells, you can do something like this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getStyle("A1:B1")->applyFromArray($style);

But, if you want to apply this style to all cells, try this:

    $style = array(
        'alignment' => array(
            'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
        )
    );

    $sheet->getDefaultStyle()->applyFromArray($style);

jQuery - replace all instances of a character in a string

RegEx is the way to go in most cases.

In some cases, it may be faster to specify more elements or the specific element to perform the replace on:

$(document).ready(function () {
    $('.myclass').each(function () {
        $('img').each(function () {
            $(this).attr('src', $(this).attr('src').replace('_s.jpg', '_n.jpg'));
        })
    })
});

This does the replace once on each string, but it does it using a more specific selector.

Row Offset in SQL Server

If you will be processing all pages in order then simply remembering the last key value seen on the previous page and using TOP (25) ... WHERE Key > @last_key ORDER BY Key can be the best performing method if suitable indexes exist to allow this to be seeked efficiently - or an API cursor if they don't.

For selecting an arbitary page the best solution for SQL Server 2005 - 2008 R2 is probably ROW_NUMBER and BETWEEN

For SQL Server 2012+ you can use the enhanced ORDER BY clause for this need.

SELECT  *
FROM     MyTable 
ORDER BY OrderingColumn ASC 
OFFSET  50 ROWS 
FETCH NEXT 25 ROWS ONLY 

Though it remains to be seen how well performing this option will be.

Multiplying Two Columns in SQL Server

This code is used to multiply the values of one column

select exp(sum(log(column))) from table

What is the difference between application server and web server?

Application server and web server both are used to host web application. Web Server is deal with web container on the other hand Application Server is deal with web container as well as EJB (Enterprise JavaBean) container or COM+ container for Microsoft dot Net.

Web Server is designed to serve HTTP static Content like HTML, images etc. and for the dynamic content have plugins to support scripting languages like Perl, PHP, ASP, JSP etc and it is limited to HTTP protocol. Below servers can generate dynamic HTTP content.

Web Server's Programming Environment:

IIS : ASP (.NET)

Apache Tomcat: Servlet

Jetty: Servlet

Apache: Php, CGI

Application Server can do whatever Web Server is capable and listens using any protocol as well as App Server have components and features to support Application level services such as Connection Pooling, Object Pooling, Transaction Support, Messaging services etc.

Application Server's Programming Environment:

MTS: COM+

WAS: EJB

JBoss: EJB

WebLogic Application Server: EJB

How to select a div element in the code-behind page?

Give ID and attribute runat='server' as :

<div class="tab-pane active" id="portlet_tab1" runat="server">

//somecode Codebehind:

Access at code behind

    Control Test = Page.FindControl("portlet_tab1");
    Test.Style.Add("display", "none"); 

    or 

    portlet_tab1.Style.Add("display", "none"); 

Pushing an existing Git repository to SVN

Git -> SVN with complete commit history

I had a Git project and had to move it to SVN. This is how I made it, keeping the whole commit history. The only thing that gets lost is the original commit time since libSVN will set the local time when we do git svn dcommit.

Howto:

  1. Have a SVN repository where we want to import our stuff to and clone it with git-svn:

    git svn clone https://path.to/svn/repository repo.git-svn`
    
  2. Go there:

    cd repo.git-svn
    
  3. Add the remote of the Git repository (in this example I'm using C:/Projects/repo.git). You want to push to SVN and give it the name old-git:

    git remote add old-git file:///C/Projects/repo.git/
    
  4. Fetch the information from the master branch from the old-git repository to the current repository:

    git fetch old-git master
    
  5. Checkout the master branch of the old-git remote into a new branch called old in the current repository:

    git checkout -b old old-git/master`
    
  6. Rebase to put the HEAD on top of old-git/master. This will maintain all your commits. What this does basically is to take all of your work done in Git and put it on top of the work you are accessing from SVN.

    git rebase master
    
  7. Now go back to your master branch:

    git checkout master
    

    And you can see that you have a clean commit history. This is what you want to push to SVN.

  8. Push your work to SVN:

    git svn dcommit
    

That's all. It is very clean, no hacking, and everything works perfectly out of the box. Enjoy.

Create a File object in memory from a string in Java

Usually when a method accepts a file, there's another method nearby that accepts a stream. If this isn't the case, the API is badly coded. Otherwise, you can use temporary files, where permission is usually granted in many cases. If it's applet, you can request write permission.

An example:

try {
    // Create temp file.
    File temp = File.createTempFile("pattern", ".suffix");

    // Delete temp file when program exits.
    temp.deleteOnExit();

    // Write to temp file
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write("aString");
    out.close();
} catch (IOException e) {
}

Can you use if/else conditions in CSS?

I've devised the below demo using a mix of tricks which allows simulating if/else scenarios for some properties. Any property which is numerical in its essence is easy target for this method, but properties with text values are.

This code has 3 if/else scenarios, for opacity, background color & width. All 3 are governed by two Boolean variables bool and its opposite notBool.

Those two Booleans are the key to this method, and to achieve a Boolean out of a none-boolean dynamic value, requires some math which luckily CSS allows using min & max functions.

Obviously those functions (min/max) are supported in recent browsers' versions which also supports CSS custom properties (variables).

_x000D_
_x000D_
var elm = document.querySelector('div')

setInterval(()=>{
  elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
_x000D_
:root{
   --color1: lightgreen;
   --color2: salmon;
   --width: 70;  /* starting value, randomly changed by javascript every 1 second */
}

div{
 --widthThreshold: 50;
 --is-width-above-limit: Min(1, Max(var(--width) - var(--widthThreshold), 0));
 --is-width-below-limit: calc(1 - var(--is-width-above-limit));
 
 --opacity-wide: .4;     /* if width is ABOVE 50 */
 --radius-narrow: 10px;  /* if width is BELOW 50 */
 --radius-wide: 60px;    /* if width is ABOVE 50 */
 --height-narrow: 80px;  /* if width is ABOVE 50 */
 --height-wide: 160px;   /* if width is ABOVE 50 */
 
 --radiusToggle: Max(var(--radius-narrow), var(--radius-wide) * var(--is-width-above-limit));
 --opacityToggle: calc(calc(1 + var(--opacity-wide)) - var(--is-width-above-limit));
 --colorsToggle: var(--color1) calc(100% * var(--is-width-above-limit)), 
                 var(--color2) calc(100% * var(--is-width-above-limit)), 
                 var(--color2) calc(100% * (1 - var(--is-width-above-limit)));
  
 --height: Max(var(--height-wide) * var(--is-width-above-limit), var(--height-narrow));
 
 height: var(--height);
 text-align: center;
 line-height: var(--height);

 width: calc(var(--width) * 1%);
 opacity: var(--opacityToggle);
 border-radius: var(--radiusToggle);
 background: linear-gradient(var(--colorsToggle));

 transition: .3s;
}

/* prints some variables */
div::before{
  counter-reset: aa var(--width);
  content: counter(aa)"%";
}

div::after{
  counter-reset: bb var(--is-width-above-limit);
  content: " is over 50% ? "counter(bb);
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Another simply way using clamp:

_x000D_
_x000D_
label{ --width: 150 }
input:checked + div{ --width: 400 }

div{
  --isWide: Clamp(0,   (var(--width) - 150) * 99999  , 1);
  width: calc(var(--width) * 1px);
  height: 150px;
  border-radius: calc(var(--isWide) * 20px); /* if wide - add radius */
  background: lightgreen;
}
_x000D_
<label>
<input type='checkbox' hidden> 
<div>Click to toggle width</div>
</label>
_x000D_
_x000D_
_x000D_

Best so far:

I have come up with a totally unique method, which is even simpler!

This method is so cool because it is so easy to implement and also to understand. it is based on animation step() function.

Since bool can be easily calculated as either 0 or 1, this value can be used in the step! if only a single step is defined, then the if/else problem is solved.

Using the keyword forwards persist the changes.

_x000D_
_x000D_
var elm = document.querySelector('div')

setInterval(()=>{
  elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
_x000D_
:root{
   --color1: salmon;
   --color2: lightgreen;
}

@keyframes if-over-threshold--container{
  to{ 
     --height: 160px;
     --radius: 30px;
     --color: var(--color2);
     opacity: .4; /* consider this as additional, never-before, style */
  }
}

@keyframes if-over-threshold--after{
  to{ 
    content: "true"; 
    color: green; 
  }
}

div{
 --width: 70;           /* must be unitless */
 --height: 80px;
 --radius: 10px;
 --color: var(--color1);
 --widthThreshold: 50;
 --is-width-over-threshold: Min(1, Max(var(--width) - var(--widthThreshold), 0));

 
 text-align: center;
 white-space: nowrap;
 transition: .3s;
 
 /* if element is narrower than --widthThreshold */
 width: calc(var(--width) * 1%);
 height: var(--height);
 line-height: var(--height);
 border-radius: var(--radius);
 background: var(--color);

 /* else */
 animation: if-over-threshold--container forwards steps(var(--is-width-over-threshold));
}

/* prints some variables */
div::before{
  counter-reset: aa var(--width);
  content: counter(aa)"% is over 50% width ? ";
}

div::after{
  content: 'false'; 
  font-weight: bold; 
  color: darkred;
  
  /* if element is wider than --widthThreshold */
  animation: if-over-threshold--after forwards steps(var(--is-width-over-threshold)) ;
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_


I've found a Chrome bug which I have reported that can affect this method in some situations where specific type of calculations is necessary, but there's a way around it.

https://bugs.chromium.org/p/chromium/issues/detail?id=1138497

In practice, what are the main uses for the new "yield from" syntax in Python 3.3?

yield from basically chains iterators in a efficient way:

# chain from itertools:
def chain(*iters):
    for it in iters:
        for item in it:
            yield item

# with the new keyword
def chain(*iters):
    for it in iters:
        yield from it

As you can see it removes one pure Python loop. That's pretty much all it does, but chaining iterators is a pretty common pattern in Python.

Threads are basically a feature that allow you to jump out of functions at completely random points and jump back into the state of another function. The thread supervisor does this very often, so the program appears to run all these functions at the same time. The problem is that the points are random, so you need to use locking to prevent the supervisor from stopping the function at a problematic point.

Generators are pretty similar to threads in this sense: They allow you to specify specific points (whenever they yield) where you can jump in and out. When used this way, generators are called coroutines.

Read this excellent tutorials about coroutines in Python for more details

CSS center content inside div

To center a div, set it's width to some value and add margin: auto.

#partners .wrap {
    width: 655px;
    margin: auto;
}

EDIT, you want to center the div contents, not the div itself. You need to change display property of h2, ul and li to inline, and remove the float: left.

#partners li, ul, h2 {
    display: inline;
    float: none;
}

Then, they will be layed out like normal text elements, and aligned according to text-align property of their container, which is what you want.

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

instead of

 http://localhost/xampp/htdocs/index.html

try just

http://localhost/index.html

or if index.html is saved in a folder in htdocs then

http://localhost/<folder-name>/index.html

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.

MySQL query String contains

be aware that this is dangerous:

WHERE `column` LIKE '%{$needle}%'

do first:

$needle = mysql_real_escape_string($needle);

so it will prevent possible attacks.

Converting a year from 4 digit to 2 digit and back again in C#

The answer is already given. But here I want to add something. Some person told that it did not work.

May be you are using

DateTime.Now.Year.ToString("yy");

that is why it is not working. I also made the same the mistake.

Change it to

DateTime.Now.ToString("yy");

How to determine if one array contains all elements of another array

Most answers based on (a1 - a2) or (a1 & a2) would not work if there are duplicate elements in either array. I arrived here looking for a way to see if all letters of a word (split to an array) were part of a set of letters (for scrabble for example). None of these answers worked, but this one does:

def contains_all?(a1, a2)
  try = a1.chars.all? do |letter|
    a1.count(letter) <= a2.count(letter)
  end
  return try
end

How to query first 10 rows and next time query other 10 rows from table

Ok. So I think you just need to implement Pagination.

$perPage = 10;

$pageNo = $_GET['page'];

Now find total rows in database.

$totalRows = Get By applying sql query;

$pages = ceil($totalRows/$perPage);    

$offset = ($pageNo - 1) * $perPage + 1

$sql = "SELECT * FROM msgtable WHERE cdate='18/07/2012' LIMIT ".$offset." ,".$perPage

Remove whitespaces inside a string in javascript

You can use

"Hello World ".replace(/\s+/g, '');

trim() only removes trailing spaces on the string (first and last on the chain). In this case this regExp is faster because you can remove one or more spaces at the same time.

If you change the replacement empty string to '$', the difference becomes much clearer:

var string= '  Q  W E   R TY ';
console.log(string.replace(/\s/g, '$'));  // $$Q$$W$E$$$R$TY$
console.log(string.replace(/\s+/g, '#')); // #Q#W#E#R#TY#

Performance comparison - /\s+/g is faster. See here: http://jsperf.com/s-vs-s

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

Pretty Printing JSON with React

Here is a demo react_hooks_debug_print.html in react hooks that is based on Chris's answer. The json data example is from https://json.org/example.html.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello World</title>
    <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/[email protected]/babel.min.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://raw.githubusercontent.com/cassiozen/React-autobind/master/src/autoBind.js"></script>

    <script type="text/babel">

let styles = {
  root: { backgroundColor: '#1f4662', color: '#fff', fontSize: '12px', },
  header: { backgroundColor: '#193549', padding: '5px 10px', fontFamily: 'monospace', color: '#ffc600', },
  pre: { display: 'block', padding: '10px 30px', margin: '0', overflow: 'scroll', }
}

let data = {
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  }
}

const DebugPrint = () => {
  const [show, setShow] = React.useState(false);

  return (
    <div key={1} style={styles.root}>
    <div style={styles.header} onClick={ ()=>{setShow(!show)} }>
        <strong>Debug</strong>
    </div>
    { show 
      ? (
      <pre style={styles.pre}>
       {JSON.stringify(data, null, 2) }
      </pre>
      )
      : null
    }
    </div>
  )
}

ReactDOM.render(
  <DebugPrint data={data} />, 
  document.getElementById('root')
);

    </script>

  </body>
</html>

Or in the following way, add the style into header:

    <style>
.root { background-color: #1f4662; color: #fff; fontSize: 12px; }
.header { background-color: #193549; padding: 5px 10px; fontFamily: monospace; color: #ffc600; }
.pre { display: block; padding: 10px 30px; margin: 0; overflow: scroll; }
    </style>

And replace DebugPrint with the follows:

const DebugPrint = () => {
  // https://stackoverflow.com/questions/30765163/pretty-printing-json-with-react
  const [show, setShow] = React.useState(false);

  return (
    <div key={1} className='root'>
    <div className='header' onClick={ ()=>{setShow(!show)} }>
        <strong>Debug</strong>
    </div>
    { show 
      ? (
      <pre className='pre'>
       {JSON.stringify(data, null, 2) }
      </pre>
      )
      : null
    }
    </div>
  )
}

Manifest merger failed : uses-sdk:minSdkVersion 14

I make all of the solutions in here with no result, so i look in another place and i found a way to trick the IDE, so you have to put a line in the Mainfest to make the Gradle use a different one, the one that you put on build.gradle the line is:

<uses-sdk tools:node="replace" />

just it, and it work.

I hope it helps.

ClassCastException, casting Integer to Double

Integer x=10;
Double y = x.doubleValue();

Git mergetool generates unwanted .orig files

Or just add

*.orig

to your global gitignore

How can I convert this foreach code to Parallel.ForEach?

string[] lines = File.ReadAllLines(txtProxyListPath.Text);

// No need for the list
// List<string> list_lines = new List<string>(lines); 

Parallel.ForEach(lines, line =>
{
    //My Stuff
});

This will cause the lines to be parsed in parallel, within the loop. If you want a more detailed, less "reference oriented" introduction to the Parallel class, I wrote a series on the TPL which includes a section on Parallel.ForEach.

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

I've posted longer answer here: https://stackoverflow.com/a/20877657/207661

TL;DR: You need only one line of code that runs in document ready event:

$(document.body).tooltip({ selector: "[title]" });

Other more complicated code suggested in other answers don't seem necessary (I've tested this with Bootstrap 3.0).

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

Paging with LINQ for objects

You're looking for the Skip and Take extension methods. Skip moves past the first N elements in the result, returning the remainder; Take returns the first N elements in the result, dropping any remaining elements.

See MSDN for more information on how to use these methods: http://msdn.microsoft.com/en-us/library/bb386988.aspx

Assuming you are already taking into account that the pageNumber should start at 0 (decrease per 1 as suggested in the comments) You could do it like this:

int numberOfObjectsPerPage = 10;
var queryResultPage = queryResult
  .Skip(numberOfObjectsPerPage * pageNumber)
  .Take(numberOfObjectsPerPage);

Otherwise as suggested by @Alvin

int numberOfObjectsPerPage = 10;
var queryResultPage = queryResult
  .Skip(numberOfObjectsPerPage * (pageNumber - 1))
  .Take(numberOfObjectsPerPage);

Change the URL in the browser without loading the new page using JavaScript

I was wondering if it will posible as long as the parent path in the page is same, only something new is appended to it.

So like let's say the user is at the page: http://domain.com/site/page.html Then the browser can let me do location.append = new.html and the page becomes: http://domain.com/site/page.htmlnew.html and the browser does not change it.

Or just allow the person to change get parameter, so let's location.get = me=1&page=1.

So original page becomes http://domain.com/site/page.html?me=1&page=1 and it does not refresh.

The problem with # is that the data is not cached (at least I don't think so) when hash is changed. So it is like each time a new page is being loaded, whereas back- and forward buttons in a non-Ajax page are able to cache data and do not spend time on re-loading the data.

From what I saw, the Yahoo history thing already loads all of the data at once. It does not seem to be doing any Ajax requests. So when a div is used to handle different method overtime, that data is not stored for each history state.

Trim whitespace from a String

Here is how you can do it:

std::string & trim(std::string & str)
{
   return ltrim(rtrim(str));
}

And the supportive functions are implemeted as:

std::string & ltrim(std::string & str)
{
  auto it2 =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( str.begin() , it2);
  return str;   
}

std::string & rtrim(std::string & str)
{
  auto it1 =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( it1.base() , str.end() );
  return str;   
}

And once you've all these in place, you can write this as well:

std::string trim_copy(std::string const & str)
{
   auto s = str;
   return ltrim(rtrim(s));
}

Try this

Validate SSL certificates with Python

M2Crypto can do the validation. You can also use M2Crypto with Twisted if you like. The Chandler desktop client uses Twisted for networking and M2Crypto for SSL, including certificate validation.

Based on Glyphs comment it seems like M2Crypto does better certificate verification by default than what you can do with pyOpenSSL currently, because M2Crypto checks subjectAltName field too.

I've also blogged on how to get the certificates Mozilla Firefox ships with in Python and usable with Python SSL solutions.

Angular ng-click with call to a controller function not working

Use alias when defining Controller in your angular configuration. For example: NOTE: I'm using TypeScript here

Just take note of the Controller, it has an alias of homeCtrl.

module MongoAngular {
    var app = angular.module('mongoAngular', ['ngResource', 'ngRoute','restangular']);

    app.config([
        '$routeProvider', ($routeProvider: ng.route.IRouteProvider) => {
            $routeProvider
                .when('/Home', {
                    templateUrl: '/PartialViews/Home/home.html',
                    controller: 'HomeController as homeCtrl'
                })
                .otherwise({ redirectTo: '/Home' });
        }])
        .config(['RestangularProvider', (restangularProvider: restangular.IProvider) => {
        restangularProvider.setBaseUrl('/api');
    }]);
} 

And here's the way to use it...

ng-click="homeCtrl.addCustomer(customer)"

Try it.. It might work for you as it worked for me... ;)

How to check if an element is in an array

Swift 2, 3, 4, 5:

let elements = [1, 2, 3, 4, 5]
if elements.contains(5) {
    print("yes")
}

contains() is a protocol extension method of SequenceType (for sequences of Equatable elements) and not a global method as in earlier releases.

Remarks:

Swift older versions:

let elements = [1,2,3,4,5]
if contains(elements, 5) {
    println("yes")
}

AngularJS - value attribute for select

If the model specified for the drop down does not exist then angular will generate an empty options element. So you will have to explicitly specify the model on the select like this:

<select ng-model="regions[index]" ng-options="....">

Refer to the following as it has been answered before:

Why does AngularJS include an empty option in select? and this fiddle

Update: Try this instead:

<select ng-model="regions[index].code" ng-options="i.code as i.name for i in regions">
</select>

or

<select ng-model="regions[2]" ng-options="r.name for r in regions">
</select>

Note that there is no empty options element in the select.

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

The verified solution doesn't work for me, since my notebook is not in my sys.path. This works however;

import os,sys
sys.path.insert(1, os.path.join(os.getcwd()  , '..'))

babel-loader jsx SyntaxError: Unexpected token

I ran into a similar issue when migrating from babel 5 to babel 6.

I was just running babel to compile the src to lib folder babel src --out-dir lib

I will share my setup for babel 6:

Ensure you have the following babel 6 devDependencies installed

"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0"

Add your .babelrc file to the project:

{
  "presets": ["es2015", "stage-0", "react"]
}

Adding header to all request with Retrofit 2

If you use addInterceptor method for add HttpLoggingInterceptor, it won't be logging the things that added by other interceptors applied later than HttpLoggingInterceptor.

For example: If you have two interceptors "HttpLoggingInterceptor" and "AuthInterceptor", and HttpLoggingInterceptor applied first, then you can't view the http-params or headers which set by AuthInterceptor.

OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addNetworkInterceptor(logging)
.addInterceptor(new AuthInterceptor());

I solved it, via using addNetworkInterceptor method.

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

that seems to be an issue with php7.3, I guess.

If you have different version installed on your system then you could use this:

php7.1 /usr/bin/composer update // or wherever your composer is

it worked for me

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

Right-click on your project's name in Eclipse's Project Explorer, then click Run As followed by Run on Server. Click the Next button. Make sure your project's name is listed in the Configured: column on the right. If it is, then you should be able to access it with this URL:

http://localhost:8085/projectname/

Additionally, whenever you make new additions (such as new JSPs, graphics or other resources) to your project, be sure to refresh the project by clicking on its name and then hitting F5. Otherwise Eclipse does not know that those new resources are available and will not make them available to Tomcat to serve.

What are the benefits of learning Vim?

Running through vimtutor only took me 30 minutes, which was enough to get familiar with vim. It was worth every second of it.

Convert or extract TTC font to TTF - how to?

This is what worked for me for extracting TTFs from .dfont and .ttc files from Mac OS X: http://transfonter.org/ttc-unpack

The resulting TTFs work fine in Windows 7.

How to create a horizontal loading progress bar?

It is Widget.ProgressBar.Horizontal on my phone, if I set android:indeterminate="true"

How do I look inside a Python object?

Try ppretty

from ppretty import ppretty


class A(object):
    s = 5

    def __init__(self):
        self._p = 8

    @property
    def foo(self):
        return range(10)


print ppretty(A(), indent='    ', depth=2, width=30, seq_length=6,
              show_protected=True, show_private=False, show_static=True,
              show_properties=True, show_address=True)

Output:

__main__.A at 0x1debd68L (
    _p = 8, 
    foo = [0, 1, 2, ..., 7, 8, 9], 
    s = 5
)

How to use unicode characters in Windows command line?

On a Windows 10 x64 machine, I made the command prompt display non-English characters by:

Open an elevated command prompt (run CMD.EXE as administrator). Query your registry for available TrueType fonts to the console by:

    REG query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont"

You'll see an output like:

    0    REG_SZ    Lucida Console
    00    REG_SZ    Consolas
    936    REG_SZ    *???
    932    REG_SZ    *MS ????

Now we need to add a TrueType font that supports the characters you need like Courier New. We do this by adding zeros to the string name, so in this case the next one would be "000":

    REG ADD "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont" /v 000 /t REG_SZ /d "Courier New"

Now we implement UTF-8 support:

    REG ADD HKCU\Console /v CodePage /t REG_DWORD /d 65001 /f

Set default font to "Courier New":

    REG ADD HKCU\Console /v FaceName /t REG_SZ /d "Courier New" /f

Set font size to 20:

    REG ADD HKCU\Console /v FontSize /t REG_DWORD /d 20 /f

Enable quick edit if you like:

    REG ADD HKCU\Console /v QuickEdit /t REG_DWORD /d 1 /f

Laravel orderBy on a relationship

I believe you can also do:

$sortDirection = 'desc';

$user->with(['comments' => function ($query) use ($sortDirection) {
    $query->orderBy('column', $sortDirection);
}]);

That allows you to run arbitrary logic on each related comment record. You could have stuff in there like:

$query->where('timestamp', '<', $someTime)->orderBy('timestamp', $sortDirection);

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

Here is a simple mail sending code with attachment

try  
{  
    SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);  
    mailServer.EnableSsl = true;  

    mailServer.Credentials = new System.Net.NetworkCredential("[email protected]", "mypassword");  

    string from = "[email protected]";  
    string to = "[email protected]";  
    MailMessage msg = new MailMessage(from, to);  
    msg.Subject = "Enter the subject here";  
    msg.Body = "The message goes here.";
    msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
    mailServer.Send(msg);  
}  
catch (Exception ex)  
{  
    Console.WriteLine("Unable to send email. Error : " + ex);  
}

Read more Sending emails with attachment in C#

How do I search within an array of hashes by hash values in ruby?

if your array looks like

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]

And you Want To know if some value is already present in your array. Use Find Method

array.find {|x| x[:name] == "Hitesh"}

This will return object if Hitesh is present in name otherwise return nil

What does the "__block" keyword mean?

From the Block Language Spec:

In addition to the new Block type we also introduce a new storage qualifier, __block, for local variables. [testme: a __block declaration within a block literal] The __block storage qualifier is mutually exclusive to the existing local storage qualifiers auto, register, and static.[testme] Variables qualified by __block act as if they were in allocated storage and this storage is automatically recovered after last use of said variable. An implementation may choose an optimization where the storage is initially automatic and only "moved" to allocated (heap) storage upon a Block_copy of a referencing Block. Such variables may be mutated as normal variables are.

In the case where a __block variable is a Block one must assume that the __block variable resides in allocated storage and as such is assumed to reference a Block that is also in allocated storage (that it is the result of a Block_copy operation). Despite this there is no provision to do a Block_copy or a Block_release if an implementation provides initial automatic storage for Blocks. This is due to the inherent race condition of potentially several threads trying to update the shared variable and the need for synchronization around disposing of older values and copying new ones. Such synchronization is beyond the scope of this language specification.

For details on what a __block variable should compile to, see the Block Implementation Spec, section 2.3.

How to set Meld as git mergetool

This worked for me on Windows 8.1 and Windows 10.

git config --global mergetool.meld.path "/c/Program Files (x86)/meld/meld.exe"

How would I access variables from one class to another?

we can access/pass arguments/variables from one class to another class using object reference.

#Class1
class Test:
    def __init__(self):
        self.a = 10
        self.b = 20
        self.add = 0

    def calc(self):
        self.add = self.a+self.b

#Class 2
class Test2:
    def display(self):
        print('adding of two numbers: ',self.add)
#creating object for Class1
obj = Test()
#invoking calc method()
obj.calc()
#passing class1 object to class2
Test2.display(obj)

how to save canvas as png image?

FileSaver.js should be able to help you here.

var canvas = document.getElementById("my-canvas");
// draw to canvas...
canvas.toBlob(function(blob) {
    saveAs(blob, "pretty image.png");
});

Reading and writing to serial port in C on Linux

Some receivers expect EOL sequence, which is typically two characters \r\n, so try in your code replace the line

unsigned char cmd[] = {'I', 'N', 'I', 'T', ' ', '\r', '\0'};

with

unsigned char cmd[] = "INIT\r\n";

BTW, the above way is probably more efficient. There is no need to quote every character.

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

react native get TextInput value

If you set the text state, why not use that directly?

_handlePress(event) {
  var username=this.state.text;

Of course the variable naming could be more descriptive than 'text' but your call.

Gradle: How to Display Test Results in the Console in Real Time?

If you are using jupiter and none of the answers work, consider verifying it is setup correctly:

test {
    useJUnitPlatform()
    outputs.upToDateWhen { false }
}

dependencies {
    testImplementation 'org.junit.jupiter:junit-jupiter-api:5.7.0'
    testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.7.0'
}

And then try the accepted answers