Programs & Examples On #Jasperserver

JasperReports Server (formerly known as JasperServer) is a stand-alone and embeddable reporting server.

How do you know if Tomcat Server is installed on your PC

In order to make

     http://localhost:8080

work, tomcat has to be started first. You can check server.xml file in conf folder for the port information. You can search if tomcat is installed on your machine. Just go to start and then type tomcat. If it is installed it will give you the directory where it is installed. Then you can select that path and run it from command prompt. Example if tomcat is installed in C:\Programfile\tomcat. You need to set this path in command prompt,go to bin folder and startup. Example: C:\Programfile\tomcat\bin\startup. Else you can also run it by directly going to the path and run startup batch file.

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

Why can't I call a public method in another class?

It sounds like you're not instantiating your class. That's the primary reason I get the "an object reference is required" error.

MyClass myClass = new MyClass();

once you've added that line you can then call your method

myClass.myMethod();

Also, are all of your classes in the same namespace? When I was first learning c# this was a common tripping point for me.

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

This happens when you declared the JSF Managed Bean as

@RequestScoped;

when you should declare as

@SessionScoped;

Regards;

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

How to get the device's IMEI/ESN programmatically in android?

For Android 6.0+ the game has changed so i suggest you use this;

The best way to go is during runtime else you get permission errors.

   /**
 * A loading screen after AppIntroActivity.
 */
public class LoadingActivity extends BaseActivity {
private static final int MY_PERMISSIONS_REQUEST_READ_PHONE_STATE = 0;
private TextView loading_tv2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loading);

    //trigger 'loadIMEI'
    loadIMEI();
    /** Fading Transition Effect */
    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
}

/**
 * Called when the 'loadIMEI' function is triggered.
 */
public void loadIMEI() {
    // Check if the READ_PHONE_STATE permission is already available.
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
            != PackageManager.PERMISSION_GRANTED) {
        // READ_PHONE_STATE permission has not been granted.
        requestReadPhoneStatePermission();
    } else {
        // READ_PHONE_STATE permission is already been granted.
        doPermissionGrantedStuffs();
    }
}



/**
 * Requests the READ_PHONE_STATE permission.
 * If the permission has been denied previously, a dialog will prompt the user to grant the
 * permission, otherwise it is requested directly.
 */
private void requestReadPhoneStatePermission() {
    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.READ_PHONE_STATE)) {
        // Provide an additional rationale to the user if the permission was not granted
        // and the user would benefit from additional context for the use of the permission.
        // For example if the user has previously denied the permission.
        new AlertDialog.Builder(LoadingActivity.this)
                .setTitle("Permission Request")
                .setMessage(getString(R.string.permission_read_phone_state_rationale))
                .setCancelable(false)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //re-request
                        ActivityCompat.requestPermissions(LoadingActivity.this,
                                new String[]{Manifest.permission.READ_PHONE_STATE},
                                MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
                    }
                })
                .setIcon(R.drawable.onlinlinew_warning_sign)
                .show();
    } else {
        // READ_PHONE_STATE permission has not been granted yet. Request it directly.
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE},
                MY_PERMISSIONS_REQUEST_READ_PHONE_STATE);
    }
}

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {

    if (requestCode == MY_PERMISSIONS_REQUEST_READ_PHONE_STATE) {
        // Received permission result for READ_PHONE_STATE permission.est.");
        // Check if the only required permission has been granted
        if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // READ_PHONE_STATE permission has been granted, proceed with displaying IMEI Number
            //alertAlert(getString(R.string.permision_available_read_phone_state));
            doPermissionGrantedStuffs();
        } else {
            alertAlert(getString(R.string.permissions_not_granted_read_phone_state));
          }
    }
}

private void alertAlert(String msg) {
    new AlertDialog.Builder(LoadingActivity.this)
            .setTitle("Permission Request")
            .setMessage(msg)
            .setCancelable(false)
            .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // do somthing here
                }
            })
            .setIcon(R.drawable.onlinlinew_warning_sign)
            .show();
}


public void doPermissionGrantedStuffs() {
    //Have an  object of TelephonyManager
    TelephonyManager tm =(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
    //Get IMEI Number of Phone  //////////////// for this example i only need the IMEI
    String IMEINumber=tm.getDeviceId();

    /************************************************
     * **********************************************
     * This is just an icing on the cake
     * the following are other children of TELEPHONY_SERVICE
     *
     //Get Subscriber ID
     String subscriberID=tm.getDeviceId();

     //Get SIM Serial Number
     String SIMSerialNumber=tm.getSimSerialNumber();

     //Get Network Country ISO Code
     String networkCountryISO=tm.getNetworkCountryIso();

     //Get SIM Country ISO Code
     String SIMCountryISO=tm.getSimCountryIso();

     //Get the device software version
     String softwareVersion=tm.getDeviceSoftwareVersion()

     //Get the Voice mail number
     String voiceMailNumber=tm.getVoiceMailNumber();


     //Get the Phone Type CDMA/GSM/NONE
     int phoneType=tm.getPhoneType();

     switch (phoneType)
     {
     case (TelephonyManager.PHONE_TYPE_CDMA):
     // your code
     break;
     case (TelephonyManager.PHONE_TYPE_GSM)
     // your code
     break;
     case (TelephonyManager.PHONE_TYPE_NONE):
     // your code
     break;
     }

     //Find whether the Phone is in Roaming, returns true if in roaming
     boolean isRoaming=tm.isNetworkRoaming();
     if(isRoaming)
     phoneDetails+="\nIs In Roaming : "+"YES";
     else
     phoneDetails+="\nIs In Roaming : "+"NO";


     //Get the SIM state
     int SIMState=tm.getSimState();
     switch(SIMState)
     {
     case TelephonyManager.SIM_STATE_ABSENT :
     // your code
     break;
     case TelephonyManager.SIM_STATE_NETWORK_LOCKED :
     // your code
     break;
     case TelephonyManager.SIM_STATE_PIN_REQUIRED :
     // your code
     break;
     case TelephonyManager.SIM_STATE_PUK_REQUIRED :
     // your code
     break;
     case TelephonyManager.SIM_STATE_READY :
     // your code
     break;
     case TelephonyManager.SIM_STATE_UNKNOWN :
     // your code
     break;

     }
     */
    // Now read the desired content to a textview.
    loading_tv2 = (TextView) findViewById(R.id.loading_tv2);
    loading_tv2.setText(IMEINumber);
}
}

Hope this helps you or someone.

How to call external url in jquery?

Follow the below simple steps you will able to get the result

Step 1- Create one internal function getDetailFromExternal in your back end. step 2- In that function call the external url by using cUrl like below function

 function getDetailFromExternal($p1,$p2) {

        $url = "http://request url with parameters";
        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true            
        ));

        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        echo $output;
        exit;
    }

Step 3- Call that internal function from your front end by using javascript/jquery Ajax.

Center text output from Graphics.DrawString()

Through a combination of the suggestions I got, I came up with this:

    private void DrawLetter()
    {
        Graphics g = this.CreateGraphics();

        float width = ((float)this.ClientRectangle.Width);
        float height = ((float)this.ClientRectangle.Width);

        float emSize = height;

        Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);

        font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);

        SizeF size = g.MeasureString(letter.ToString(), font);
        g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);

    }

    private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
    {
        // Compute actual size, shrink if needed
        while (true)
        {
            SizeF size = g.MeasureString(text, font);

            // It fits, back out
            if (size.Height <= proposedSize.Height &&
                 size.Width <= proposedSize.Width) { return font; }

            // Try a smaller font (90% of old size)
            Font oldFont = font;
            font = new Font(font.Name, (float)(font.Size * .9), font.Style);
            oldFont.Dispose();
        }
    }

So far, this works flawlessly.

The only thing I would change is to move the FindBestFitFont() call to the OnResize() event so that I'm not calling it every time I draw a letter. It only needs to be called when the control size changes. I just included it in the function for completeness.

Sum values in foreach loop php

Use +=

$val = 0;

foreach($arr as $var) {
   $val += $var; 
}

echo $val;

Calling a parent window function from an iframe

I recently had to find out why this didn't work too.

The javascript you want to call from the child iframe needs to be in the head of the parent. If it is in the body, the script is not available in the global scope.

<head>
    <script>
    function abc() {
        alert("sss");
    }
    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="parent.abc();" href="#">Click Me</a>
    </iframe>
</body>

Hope this helps anyone that stumbles upon this issue again.

How to delete from a text file, all lines that contain a specific string?

You may consider using ex (which is a standard Unix command-based editor):

ex +g/match/d -cwq file

where:

  • + executes given Ex command (man ex), same as -c which executes wq (write and quit)
  • g/match/d - Ex command to delete lines with given match, see: Power of g

The above example is a POSIX-compliant method for in-place editing a file as per this post at Unix.SE and POSIX specifications for ex.


The difference with sed is that:

sed is a Stream EDitor, not a file editor.BashFAQ

Unless you enjoy unportable code, I/O overhead and some other bad side effects. So basically some parameters (such as in-place/-i) are non-standard FreeBSD extensions and may not be available on other operating systems.

How to set the context path of a web application in Tomcat 7.0

It's not recommended to update the server configuration like server.xml or ROOT.xml.

You can put a context.xml configuration file under your web-application META-INF directory, with the context path setting included. This will override the default server setting?

i.e.:

<Context docBase="yourAppName" path="/yourAppPath" reloadable="true">

Use '=' or LIKE to compare strings in SQL?

LIKE and the equality operator have different purposes, they don't do the same thing:
= is much faster, whereas LIKE can interpret wildcards. Use = wherever you can and LIKE wherever you must.

SELECT * FROM user WHERE login LIKE 'Test%';

Sample matches:

TestUser1
TestUser2
TestU
Test

Resizable table columns with jQuery

:-) Once I found myself in the same situation, there was no jQuery plugin matching my requeriments, so I spend some time developing my own one: colResizable
 

About colResizable

colResizable is a free jQuery plugin to resize table columns dragging them manually. It is compatible with both mouse and touch devices and has some nice features such as layout persistence after page refresh or postback. It works with both percentage and pixel-based table layouts.

It is tiny in size (colResizable 1.0 is only 2kb) and it is fully compatible with all major browsers (IE7+, Firefox, Chrome and Opera).

enter image description here

Features

colResizable was developed since no other similar plugin with the below listed features was found:

  • Compatible with mouse and touch devices (PC, tablets, and mobile phones)
  • Compatibility with both percentage and pixel-based table layouts
  • Column resizing not altering total table width (optional)
  • No external resources needed (such as images or stylesheets)
  • Optional layout persistence after page refresh or postback
  • Customization of column anchors
  • Small footprint
  • Cross-browser compatibility (IE7+, Chrome, Safari, Firefox)
  • Events

Comparison with other plugins

colResizable is the most polished plugin to resize table columns out there. It has plenty of customization possibilities and it is also compatible with touch devices. But probably the most interesting feature which is making colResizable the greatest choice is that it is compatible with both pixel-based and fluid percentage table layouts. But, what does it mean?

If the width of a table is set to, lets say 90%, and the column widths are modified using colResizable, when the browser is resized columns widths are resized proportionally. While other plugins does behave odd, colResizable does its job just as expected.

colResizable is also compatible with table max-width attribute: if the sum of all columns exceed the table's max-width, they are automatically fixed and updated.

Another great advantage compared with other plugins is that it is compatible with page refresh, postbacks and even partial postbacks if the table is located inside of an updatePanel. It is compatible with all major browsers (IE7+, Firefox, Chrome and Opera), while other plugins fail with old IE versions.

See samples and JSFiddle.

Code sample

$("#sample").colResizable({
        liveDrag:true
});

When to use React "componentDidUpdate" method?

This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop. Take a look at the example below that shows a typical usage example of this lifecycle method.

componentDidUpdate(prevProps) {
 //Typical usage, don't forget to compare the props
 if (this.props.userName !== prevProps.userName) {
   this.fetchData(this.props.userName);
 }
}

Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.

For more info, refer to the official docs:

C++ code file extension? .cc vs .cpp

The .cc extension is necessary for using implicit rules within makefiles. Look through these links to get a better understanding of makefiles, but look mainly the second one, as it clearly says the usefulness of the .cc extension:

ftp://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter/make_2.html

https://ftp.gnu.org/old-gnu/Manuals/make-3.79.1/html_chapter/make_10.html

I just learned of this now.

Angular ReactiveForms: Producing an array of checkbox values?

Add my 5 cents) My question model

{
   name: "what_is_it",
   options:[
     {
      label: 'Option name',
      value: '1'
     },
     {
      label: 'Option name 2',
      value: '2'
     }
   ]
}

template.html

<div class="question"  formGroupName="{{ question.name }}">
<div *ngFor="let opt of question.options; index as i" class="question__answer" >
  <input 
    type="checkbox" id="{{question.name}}_{{i}}"
    [name]="question.name" class="hidden question__input" 
    [value]="opt.value" 
    [formControlName]="opt.label"
   >
  <label for="{{question.name}}_{{i}}" class="question__label question__label_checkbox">
      {{opt.label}}
  </label>
</div>

component.ts

 onSubmit() {
    let formModel = {};
    for (let key in this.form.value) {
      if (typeof this.form.value[key] !== 'object') { 
        formModel[key] = this.form.value[key]
      } else { //if formgroup item
        formModel[key] = '';
        for (let k in this.form.value[key]) {
          if (this.form.value[key][k])
            formModel[key] = formModel[key] + k + ';'; //create string with ';' separators like 'a;b;c'
        }
      }
    }
     console.log(formModel)
   }

Remote desktop connection protocol error 0x112f

If the server accessible with RPC (basically, if you can access a shared folder on it), you could free some memory and thus let the RDP service work properly. The following windows native commands can be used:

To get the list of memory consuming tasks:

tasklist /S <remote_server> /V /FI "MEMUSAGE gt 10000"

To kill a task by its name:

taskkill /S <remote_server> /IM <process_image_name> /F

To show the list of desktop sessions:

qwinsta.exe /SERVER:<remote_server>

To close an old abandoned desktop session:

logoff <session_id> /SERVER:<remote_server> 

After some memory is freed, the RDP should start working.

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

Jump to function definition in vim

Another common technique is to place the function name in the first column. This allows the definition to be found with a simple search.

int
main(int argc, char *argv[])
{
    ...
}

The above function could then be found with /^main inside the file or with :grep -r '^main' *.c in a directory. As long as code is properly indented the only time the identifier will occur at the beginning of a line is at the function definition.

Of course, if you aren't using ctags from this point on you should be ashamed of yourself! However, I find this coding standard a helpful addition as well.

Passing multiple variables to another page in url

Use the ampersand & to glue variables together:

$url = "http://localhost/main.php?email=$email_address&event_id=$event_id";
//                               ^ start of vars      ^next var

How do I import/include MATLAB functions?

You should be able to put them in your ~/matlab on unix.

I'm not sure which directory matlab looks in for windows, but you should be able to figure it out by executing userpath from the matlab command line.

Java random numbers using a seed

Several of the examples here create a new Random instance, but this is unnecessary. There is also no reason to use synchronized as one solution does. Instead, take advantage of the methods on the ThreadLocalRandom class:

double randomGenerator() {
    return ThreadLocalRandom.current().nextDouble(0.5);
}

Get a UTC timestamp

"... that are independent of their timezone"

var timezone =  d.getTimezoneOffset() // difference in minutes from GMT

Reverse HashMap keys and values in Java

If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, List<String>> mapInversed = 
map.entrySet()
   .stream()
   .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))

How to sort a list of objects based on an attribute of the objects?

# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)

More on sorting by keys.

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

Use:

  public void onClick(View v) {

    switch(v.getId()){

      case R.id.Button_MyCards: /** Start a new Activity MyCards.java */
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
        break;

      case R.id.Button_Exit: /** AlerDialog when click on Exit */
        MyAlertDialog();
        break;
    }
}

Note that this will not work in Android library projects (due to http://tools.android.com/tips/non-constant-fields) where you will need to use something like:

int id = view.getId();
if (id == R.id.Button_MyCards) {
    action1();
} else if (id == R.id.Button_Exit) {
    action2();
}

Hiding an Excel worksheet with VBA

You can do this programmatically using a VBA macro. You can make the sheet hidden or very hidden:

Sub HideSheet()

    Dim sheet As Worksheet

    Set sheet = ActiveSheet

    ' this hides the sheet but users will be able 
    ' to unhide it using the Excel UI
    sheet.Visible = xlSheetHidden

    ' this hides the sheet so that it can only be made visible using VBA
    sheet.Visible = xlSheetVeryHidden

End Sub

How to combine multiple inline style objects?

For ones that looking this solution in React, If you want to use the spread operator inside style, you should use: babel-plugin-transform-object-rest-spread.

Install it by npm module and configure your .babelrc as such:

{
  "presets": ["env", "react"],
  "plugins": ["transform-object-rest-spread"]
}

Then you can use like...

const sizing = { width: 200, height: 200 }
 <div
   className="dragon-avatar-image-background"
   style={{ backgroundColor: blue, ...sizing }}
  />

More info: https://babeljs.io/docs/en/babel-plugin-transform-object-rest-spread/

How to "set a breakpoint in malloc_error_break to debug"

I had the same problem with Xcode. I followed steps you gave and it didn't work. I became crazy because in every forum I saw, all clues for this problem are the one you gave. I finally saw I put a space after the malloc_error_break, I suppressed it and now it works. A dumb problem but if the solution doesn't work, be sure you haven't put any space before and after the malloc_error_break.

Hope this message will help..

Center text in div?

Add to the selector containing the text

margin:auto;

In jQuery, how do I select an element by its name attribute?

If you'd like to know the value of the default selected radio button before a click event, try this:

alert($("input:radio:checked").val());

What do >> and << mean in Python?

These are the shift operators

x << y Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y Returns x with the bits shifted to the right by y places. This is the same as //'ing x by 2**y.

Convert a string into an int

NSString *string = /* Assume this exists. */;
int value = [string intValue];

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

Determine if a String is an Integer in Java

As an alternative approach to trying to parse the string and catching NumberFormatException, you could use a regex; e.g.

if (Pattern.compile("-?[0-9]+").matches(str)) {
    // its an integer
}

This is likely to be faster, especially if you precompile and reuse the regex.

However, the problem with this approach is that Integer.parseInt(str) will also fail if str represents a number that is outside range of legal int values. While it is possible to craft a regex that only matches integers in the range Integer.MIN_INT to Integer.MAX_INT, it is not a pretty sight. (And I am not going to try it ...)

On the other hand ... it may be acceptable to treat "not an integer" and "integer too large" separately for validation purposes.

Correct way to focus an element in Selenium WebDriver using Java

You can use JS as below:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("document.getElementById('elementid').focus();");

How to change the default port of mysql from 3306 to 3360

When server first starts the my.ini may not be created where everyone has stated. I was able to find mine in C:\Documents and Settings\All Users\Application Data\MySQL\MySQL Server 5.6

This location has the defaults for every setting.

# CLIENT SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by MySQL client applications.
# Note that only client applications shipped by MySQL are guaranteed
# to read this section. If you want your own MySQL client program to
# honor these values, you need to specify it as an option during the
# MySQL client library initialization.
#
[client]

# pipe
# socket=0.0
port=4306  !!!!!!!!!!!!!!!!!!!Change this!!!!!!!!!!!!!!!!!

[mysql]
no-beep

default-character-set=utf8

How does a ArrayList's contains() method evaluate objects?

Just wanted to note that the following implementation is wrong when value is not a primitive type:

public class Thing
{
    public Object value;  

    public Thing (Object x)
    {
        this.value = x;
    }

    @Override
    public boolean equals(Object object)
    {
        boolean sameSame = false;

        if (object != null && object instanceof Thing)
        {
            sameSame = this.value == ((Thing) object).value;
        }

        return sameSame;
    }
}

In that case I propose the following:

public class Thing {
    public Object value;  

    public Thing (Object x) {
        value = x;
    }

    @Override
    public boolean equals(Object object) {

        if (object != null && object instanceof Thing) {
            Thing thing = (Thing) object;
            if (value == null) {
                return (thing.value == null);
            }
            else {
                return value.equals(thing.value);
            }
        }

        return false;
    }
}

How do I delete all the duplicate records in a MySQL table without temp tables

Add Unique Index on your table:

ALTER IGNORE TABLE TableA   
ADD UNIQUE INDEX (member_id, quiz_num, question_num, answer_num);

is work very well

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Had this issue after a reinstall today. Make sure the Application Experience service is started and not set to disabled. If its set to manual, I believe VS will start it.

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I experienced a similar problem, I was getting ERR_HTTP2_PROTOCOL_ERROR on one of the HTTP GET requests.

I noticed that the Chrome update was pending, so I updated the Chrome browser to the latest version and the error was gone next time when I relaunched the browser.

how to run mysql in ubuntu through terminal

You have to give a valid username. For example, to run query with user root you have to type the following command and then enter password when prompted:

mysql -u root -p

Once you are connected, prompt will be something like:

mysql>

Here you can write your query, after database selection, for example:

mysql> USE your_database;
mysql> SELECT * FROM your_table;

DataTable: Hide the Show Entries dropdown but keep the Search box

To disable the "Show Entries" label, add the code dom: 'Bfrtip' or you can add "bInfo": false

$('#example').DataTable({
    dom: 'Bfrtip'
})

How do you make an anchor link non-clickable or disabled?

The cleanest method would be to add a class with pointer-events:none when you want to disable a click. It would function like a normal label.

.disableClick{
    pointer-events: none;
}

How to set the margin or padding as percentage of height of parent container?

Other way to center one line text is:

.parent{
  position: relative;
}

.child{
   position: absolute;
   top: 50%;
   line-height: 0;
}

or just

.parent{
  overflow: hidden; /* if this ins't here the parent will adopt the 50% margin of the child */
}

.child{
   margin-top: 50%;
   line-height: 0;
}

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

I resolve this is by changing the version no of recyleview to recyclerview-v7:24.2.1. Please check your dependencies and use the proper version number.

How can I find out if an .EXE has Command-Line Options?

Just use IDA PRO (https://www.hex-rays.com/products/ida/index.shtml) to disassemble the file, and search for some known command line option (using Search...Text) - in that section you will then typically see all the command line options - for the program (LIB2NIST.exe) in the screenshot below, for example, it shows a documented command line option (/COM2TAG) but also some undocumented ones, like /L. Hope this helps?

enter image description here

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

I used James Nelli answer and added onpaste="return false;" (Håvard Geithus) to ensure only integer is entered into the input. Even if you tried to paste, it will not allow it.

Unable to Install Any Package in Visual Studio 2015

Change the "package source" in nuget to All

Details: None of the above helped in my case. My problem was that I restricted to only one private feed. Once I changed the "package source" to All, my problem was solved. I believe the crux of the matter is that my private pkg has a dependency on other pkgs from nuget.org.

I hope this can help someone

LAST_INSERT_ID() MySQL

For no InnoDB solution: you can use a procedure don't forgot to set the delimiter for storing the procedure with ;

CREATE PROCEDURE myproc(OUT id INT, IN otherid INT, IN title VARCHAR(255))
BEGIN
LOCK TABLES `table1` WRITE;
INSERT INTO `table1` ( `title` ) VALUES ( @title ); 
SET @id = LAST_INSERT_ID();
UNLOCK TABLES;
INSERT INTO `table2` ( `parentid`, `otherid`, `userid` ) VALUES (@id, @otherid, 1); 
END

And you can use it...

SET @myid;
CALL myproc( @myid, 1, "my title" );
SELECT @myid;

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

Edit a commit message in SourceTree Windows (already pushed to remote)

On Version 1.9.6.1. For UnPushed commit.

  1. Click on previously committed description
  2. Click Commit icon
  3. Enter new commit message, and choose "Ammend latest commit" from the Commit options dropdown.
  4. Commit your message.

jQuery UI Accordion Expand/Collapse All

Yes, it is possible. Put all div in separate accordion class as follows:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>

<script type="text/javascript">

        $(function () {
            $("input[type=submit], button")
        .button()
        .click(function (event) {
            event.preventDefault();
        });
            $("#tabs").tabs();
            $(".accordion").accordion({
                heightStyle: "content",

                collapsible: true,
                active: 0



            });
        });

function expandAll()
{
  $(".accordion").accordion({
                heightStyle: "content",

                collapsible: true,
                active: 0

            });

            return false;   
}

function collapseAll()
{
  $(".accordion").accordion({
                heightStyle: "content",

                collapsible: true,
                active: false



            });
            return false;
}
</script>



<div class="accordion">
  <h3>Toggle 1</h3>
  <div >
    <p>text1.</p>
  </div>
</div>
<div class="accordion">
  <h3>Toggle 2</h3>
  <div >
    <p>text2.</p>
  </div>
</div>
<div class="accordion">
  <h3>Toggle 3</h3>
  <div >
    <p>text3.</p>
  </div>
</div>

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

SQL Server PRINT SELECT (Print a select query result)?

You know, there might be an easier way but the first thing that pops to mind is:

Declare @SumVal int;
Select @SumVal=Sum(Amount) From Expense;
Print @SumVal;

You can, of course, print any number of fields from the table in this way. Of course, if you want to print all of the results from a query that returns multiple rows, you'd just direct your output appropriately (e.g. to Text).

Replace all particular values in a data frame

Since PikkuKatja and glallen asked for a more general solution and I cannot comment yet, I'll write an answer. You can combine statements as in:

> df[df=="" | df==12] <- NA
> df
     A    B
1  <NA> <NA>
2  xyz  <NA>
3  jkl  100

For factors, zxzak's code already yields factors:

> df <- data.frame(list(A=c("","xyz","jkl"), B=c(12,"",100)))
> str(df)
'data.frame':   3 obs. of  2 variables:
 $ A: Factor w/ 3 levels "","jkl","xyz": 1 3 2
 $ B: Factor w/ 3 levels "","100","12": 3 1 2

If in trouble, I'd suggest to temporarily drop the factors.

df[] <- lapply(df, as.character)

'Syntax Error: invalid syntax' for no apparent reason

You're missing a close paren in this line:

fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494

There are three ( and only two ).
I hope This will help you.

Yarn install command error No such file or directory: 'install'

sudo npm install -g yarnpkg
npm WARN deprecated [email protected]: Please use the `yarn` package instead of `yarnpkg`

so this works for me

sudo npm install -g yarn

Python: TypeError: object of type 'NoneType' has no len()

You don't need to assign names to list or [] or anything else until you wish to use it.

It's neater to use a list comprehension to make the list of names.

shuffle modifies the list you pass to it. It always returns None

If you are using a context manager (with ...) you don't need to close the file explicitly

from random import shuffle

with open('names') as f:
    names = [name.rstrip() for name in f if not name.isspace()]
    shuffle(names)

assert len(names) > 100

How to input matrix (2D list) in Python?

Apart from the accepted answer, you can also initialise your rows in the following manner - matrix[i] = [0]*n

Therefore, the following piece of code will work -

m = int(input('number of rows, m = '))
n = int(input('number of columns, n = '))
matrix = []
# initialize the number of rows
for i in range(0,m):
    matrix += [0]
# initialize the matrix
for i in range (0,m):
    matrix[i] = [0]*n
for i in range (0,m):
    for j in range (0,n):
        print ('entry in row: ',i+1,' column: ',j+1)
        matrix[i][j] = int(input())
print (matrix)

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

How can I schedule a daily backup with SQL Server Express?

We have used the combination of:

  1. Cobian Backup for scheduling/maintenance

  2. ExpressMaint for backup

Both of these are free. The process is to script ExpressMaint to take a backup as a Cobian "before Backup" event. I usually let this overwrite the previous backup file. Cobian then takes a zip/7zip out of this and archives these to the backup folder. In Cobian you can specify the number of full copies to keep, make multiple backup cycles etc.

ExpressMaint command syntax example:

expressmaint -S HOST\SQLEXPRESS -D ALL_USER -T DB -R logpath -RU WEEKS -RV 1 -B backuppath -BU HOURS -BV 3 

Fatal error: [] operator not supported for strings

this was available in php 5.6 in php 7+ you should declare the array first

$users = array(); // not $users = ";
$users[] = "762";

Setting PATH environment variable in OSX permanently

If you are using zsh do the following.

  1. Open .zshrc file nano $HOME/.zshrc

  2. You will see the commented $PATH variable here

    # If you come from bash you might have to change your $PATH.
    # export PATH=$HOME/bin:/usr/local/...

  3. Remove the comment symbol(#) and append your new path using a separator(:) like this.

export PATH=$HOME/bin:/usr/local/bin:/Users/ebin/Documents/Softwares/mongoDB/bin:$PATH

  1. Activate the change source $HOME/.zshrc

You're done !!!

Calling constructors in c++ without new

I played a bit with it and the syntax seems to get quite strange when a constructor takes no arguments. Let me give an example:

#include <iostream> 

using namespace std;

class Thing
{
public:
    Thing();
};

Thing::Thing()
{
    cout << "Hi" << endl;
}

int main()
{
    //Thing myThing(); // Does not work
    Thing myThing; // Works

}

so just writing Thing myThing w/o brackets actually calls the constructor, while Thing myThing() makes the compiler thing you want to create a function pointer or something ??!!

How to declare a global variable in JavaScript

If this is the only application where you're going to use this variable, Felix's approach is excellent. However, if you're writing a jQuery plugin, consider "namespacing" (details on the quotes later...) variables and functions needed under the jQuery object. For example, I'm currently working on a jQuery popup menu that I've called miniMenu. Thus, I've defined a "namespace" miniMenu under jQuery, and I place everything there.

The reason I use quotes when I talk about JavaScript namespaces is that they aren't really namespaces in the normal sense. Instead, I just use a JavaScript object and place all my functions and variables as properties of this object.

Also, for convenience, I usually sub-space the plugin namespace with an i namespace for stuff that should only be used internally within the plugin, so as to hide it from users of the plugin.

This is how it works:

// An object to define utility functions and global variables on:
$.miniMenu = new Object();
// An object to define internal stuff for the plugin:
$.miniMenu.i = new Object();

Now I can just do $.miniMenu.i.globalVar = 3 or $.miniMenu.i.parseSomeStuff = function(...) {...} whenever I need to save something globally, and I still keep it out of the global namespace.

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

One other cause to this problem is if you open a project from a mapped drive - Visual Studio handles such projects properly, but apparently Nunit doesn't support them.

Copying the project to a physical fixed the issue.

Bootstrap 3, 4 and 5 .container-fluid with grid adding unwanted padding

I think no one has given the correct answer to the question. My working solution is : 1. Just declare another class along with container-fluid class example(.maxx):

_x000D_
_x000D_
 <div class="container-fluid maxx">_x000D_
   <div class="row">_x000D_
     <div class="col-sm-12">_x000D_
     <p>Hello</p>_x000D_
     </div>_x000D_
   </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

  1. Then using specificity in the css part do this:

_x000D_
_x000D_
.container-fluid.maxx {_x000D_
  padding-left: 0px;_x000D_
  padding-right: 0px; }
_x000D_
_x000D_
_x000D_

This will work 100% and will remove the padding from left and right. I hope this helps.

How do I decrease the size of my sql server log file?

I had the same problem, my database log file size was about 39 gigabyte, and after shrinking (both database and files) it reduced to 37 gigabyte that was not enough, so I did this solution: (I did not need the ldf file (log file) anymore)

(**Important) : Get a full backup of your database before the process.

  1. Run "checkpoint" on that database.

  2. Detach that database (right click on the database and chose tasks >> Detach...) {if you see an error, do the steps in the end of this text}

  3. Move MyDatabase.ldf to another folder, you can find it in your hard disk in the same folder as your database (Just in case you need it in the future for some reason such as what user did some task).

  4. Attach the database (right click on Databases and chose Attach...)

  5. On attach dialog remove the .ldf file (which shows 'file not found' comment) and click Ok. (don`t worry the ldf file will be created after the attachment process.)

  6. After that, a new log file create with a size of 504 KB!!!.

In step 2, if you faced an error that database is used by another user, you can:

1.run this command on master database "sp_who2" and see what process using your database.

2.read the process number, for example it is 52 and type "kill 52", now your database is free and ready to detach.

If the number of processes using your database is too much:

1.Open services (type services in windows start) find SQL Server ... process and reset it (right click and chose reset).

  1. Immediately click Ok button in the detach dialog box (that showed the detach error previously).

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

This was enough for me:

sudo apt-get install build-essential

Removing Spaces from a String in C?

Here is the simplest thing i could think of. Note that this program uses second command line argument (argv[1]) as a line to delete whitespaces from.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/*The function itself with debug printing to help you trace through it.*/

char* trim(const char* str)
{
    char* res = malloc(sizeof(str) + 1);
    char* copy = malloc(sizeof(str) + 1);
    copy = strncpy(copy, str, strlen(str) + 1);
    int index = 0;

    for (int i = 0; i < strlen(copy) + 1; i++) {
        if (copy[i] != ' ')
        {
            res[index] = copy[i];
            index++;
        }
        printf("End of iteration %d\n", i);
        printf("Here is the initial line: %s\n", copy);
        printf("Here is the resulting line: %s\n", res);
        printf("\n");
    }
    return res;
}

int main(int argc, char* argv[])
{
    //trim function test

    const char* line = argv[1];
    printf("Here is the line: %s\n", line);

    char* res = malloc(sizeof(line) + 1);
    res = trim(line);

    printf("\nAnd here is the formatted line: %s\n", res);

    return 0;
}

Import cycle not allowed

You may have imported,

project/controllers/base

inside the

project/controllers/routes

You have already imported before. That's not supported.

firefox proxy settings via command line

All the other answers here explain how to program your proxy settings into Firefox which is what WPAD was invented to do. If you have WPAD configured then just tell Firefox to use it to auto-detect its settings, as you would in the GUI.

Connection Settings

To do this from a cmd file or command line:

pushd "%APPDATA%\Mozilla\Firefox\Profiles\*.default"
echo user_pref("network.proxy.type", 4);>>prefs.js
popd

This of course requires you to have WPAD configured and working correctly. Also I believe prefs.js won't exist until you've run Firefox once.

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

In my own case I have the following error

Illegal mix of collations (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for operation '='

$this->db->select("users.username as matric_no, CONCAT(users.surname, ' ', users.first_name, ' ', users.last_name) as fullname") ->join('users', 'users.username=classroom_students.matric_no', 'left') ->where('classroom_students.session_id', $session) ->where('classroom_students.level_id', $level) ->where('classroom_students.dept_id', $dept);

After weeks of google searching I noticed that the two fields I am comparing consists of different collation name. The first one i.e username is of utf8_general_ci while the second one is of utf8_unicode_ci so I went back to the structure of the second table and changed the second field (matric_no) to utf8_general_ci and it worked like a charm.

Saving numpy array to txt file row wise

I know this is old, but none of these answers solved the root problem of numpy not saving the array row-wise. I found that this one liner did the trick for me:

b = np.matrix(a)
np.savetxt("file", b)

What is the best way to access redux store outside a react component?

You can use store object that is returned from createStore function (which should be already used in your code in app initialization). Than you can use this object to get current state with store.getState() method or store.subscribe(listener) to subscribe to store updates.

You can even save this object to window property to access it from any part of application if you really want it (window.store = store)

More info can be found in the Redux documentation .

iOS: present view controller programmatically

Here is how you can do it in Swift:

let vc = UIViewController()
self.presentViewController(vc, animated: true, completion: nil)

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

FIX FOR MYSQL IN DOCKER

I'm using @fefe's excellent answer here to show how to fix this problem within some minutes when using docker (via docker-compose). It's quite easy as you don't have to touch MySQL's configuration files, but it requires you to export and import your entire data:

The default situation of your MySQL setup probably looks like this. Your data is saved inside the data-mysql volume.

mysql:
  image: mysql:5.7.25
  container_name: mysql
  restart: always
  volumes:
    - data-mysql:/var/lib/mysql
  environment:
    - "MYSQL_DATABASE=XXX"
    - "MYSQL_USER=XXX"
    - "MYSQL_PASSWORD=XXX"
    - "MYSQL_ROOT_PASSWORD=XXX"
  expose:
    - 3306
  1. Make a backup of your entire data/database via SQL export, so you have a .sql.gz or something. I'm using Adminer for this.

  2. To fix (and as explained in @fefe's answer) we have to setup the MySQL instance from zero, meaning we have to delete the mysql docker container and the mysql volume docker container. Do a docker container ls and a docker volume ls to see all your containers and volumes, and pick the two names that are your mysql instance and your mysql volume, for me it's mysql (container) and docker_data-mysql (volume).

  3. Stop your running instances via docker-compose down (or however you usually stop your docker stuff).

  4. To delete them, I do docker container rm mysql and docker volume rm docker_data-mysql (note that there is an underscore AND a dash in the name).

  5. Add these settings to your mysql block in your docker setup:

mysql:
  image: mysql:5.7.25
  command: ['--innodb_page_size=64k', '--innodb_log_buffer_size=32M', '--innodb_buffer_pool_size=512M']
  container_name: mysql
  # ...
  1. Restart your instances, the mysql and mysql volume should be build automatically, now with the new settings.

  2. Import your database dump file, maybe with:

gzip -dc < database.sql.gz | docker exec -i mysql mysql -uroot -pYOURPASSWORD

Voila! Worked very fine for me!

TSQL Default Minimum DateTime

I agree with the sentiment in "don't use magic values". But I would like to point out that there are times when it's legit to resort to such solutions.

There is a price to pay for setting columns nullable: NULLs are not indexable. A query like "get all records that haven't been modified since the start of 2010" includes those that have never been modified. If we use a nullable column we're thus forced to use [modified] < @cutoffDate OR [modified] IS NULL, and this in turn forces the database engine to perform a table scan, since the nulls are not indexed. And this last can be a problem.

In practice, one should go with NULL if this does not introduce a practical, real-world performance penalty. But it can be difficult to know, unless you have some idea what realistic data volumes are today and will be in the so-called forseeable future. You also need to know if there will be a large proportion of the records that have the special value - if so, there's no point in indexing it anyway.

In short, by deafult/rule of thumb one should go for NULL. But if there's a huge number of records, the data is frequently queried, and only a small proportion of the records have the NULL/special value, there could be significant performance gain for locating records based on this information (provided of course one creates the index!) and IMHO this can at times justify the use of "magic" values.

Django - iterate number in for loop of a template

{% for days in days_list %}
    <h2># Day {{ forloop.counter }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
{% endfor %}

or if you want to start from 0

{% for days in days_list %}
        <h2># Day {{ forloop.counter0 }} - From {{ days.from_location }} to {{ days.to_location }}</h2>
    {% endfor %}

How to make the background DIV only transparent using CSS

I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.

Which mean:

<div id="a">
<div id="b">
</div></div>

Div#a has 0.6 opacity
div#b has 1 opacity

Has #b is within #a then it's maximum opacity is always 0.6

If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity

ImportError: No module named PIL

I had the same problem and i fixed it by checking what version pip (pip3 --version) is, then realizing I'm typing python<uncorrect version> filename.py instead of python<correct version> filename.py

make sounds (beep) with c++

Here's one way:

cout << '\a';

From C++ Character Constants:

Alert: \a

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

You can set the line-height in pixels instead of percentage. Is that what you mean?

HttpContext.Current.Session is null when routing requests

It seems that you have forgotten to add your state server address in the config file.

 <sessionstate mode="StateServer" timeout="20" server="127.0.0.1" port="42424" />

Scale the contents of a div by a percentage?

You can simply use the zoom property:

#myContainer{
    zoom: 0.5;
    -moz-transform: scale(0.5);
}

Where myContainer contains all the elements you're editing. This is supported in all major browsers.

Select all columns except one in MySQL?

I agree with @Mahomedalid's answer, but I didn't want to do something like a prepared statement and I didn't want to type all the fields, so what I had was a silly solution.

Go to the table in phpmyadmin->sql->select, it dumps the query: copy, replace and done! :)

Why are only final variables accessible in anonymous class?

An anonymous class is an inner class and the strict rule applies to inner classes (JLS 8.1.3):

Any local variable, formal method parameter or exception handler parameter used but not declared in an inner class must be declared final. Any local variable, used but not declared in an inner class must be definitely assigned before the body of the inner class.

I haven't found a reason or an explanation on the jls or jvms yet, but we do know, that the compiler creates a separate class file for each inner class and it has to make sure, that the methods declared on this class file (on byte code level) at least have access to the values of local variables.

(Jon has the complete answer - I keep this one undeleted because one might interested in the JLS rule)

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

Aligning a button to the center

You should use something like this:

<div style="text-align:center">  
    <input type="submit" />  
</div>  

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.

<input type="submit" style="width: 300px; margin: 0 auto;" />

How to destroy a DOM element with jQuery?

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

How can I programmatically check whether a keyboard is present in iOS app?

I think you need to use the notifications that are provided about the keyboard:

From: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITextField_Class/Reference/UITextField.html

Keyboard Notifications

When the system shows or hides the keyboard, it posts several keyboard notifications. These notifications contain information about the keyboard, including its size, which you can use for calculations that involve moving views. Registering for these notifications is the only way to get some types of information about the keyboard. The system delivers the following notifications for keyboard-related events:

* UIKeyboardWillShowNotification
* UIKeyboardDidShowNotification
* UIKeyboardWillHideNotification
* UIKeyboardDidHideNotification

For more information about these notifications, see their descriptions in UIWindow Class Reference. For information about how to show and hide the keyboard, see Text and Web.

Ignore python multiple return value

Three simple choices.

Obvious

x, _ = func()

x, junk = func()

Hideous

x = func()[0]

And there are ways to do this with a decorator.

def val0( aFunc ):
    def pick0( *args, **kw ):
        return aFunc(*args,**kw)[0]
    return pick0

func0= val0(func)

How to read a list of files from a folder using PHP?

The simplest and most fun way (imo) is glob

foreach (glob("*.*") as $filename) {
    echo $filename."<br />";
}

But the standard way is to use the directory functions.

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            echo "filename: .".$file."<br />";
        }
        closedir($dh);
    }
}

There are also the SPL DirectoryIterator methods. If you are interested

Add horizontal scrollbar to html table

//Representation of table
<div class="search-table-outter">
<table class="table table-responsive search-table inner">
</table>
</div>

//Css to make Horizontal Dropdown

<style>

    .search-table{table-layout: auto; margin:40px auto 0px auto; }
    .search-table, td, th {
        border-collapse: collapse;
    }
th{padding:20px 7px; font-size:15px; color:#444;}
td{padding:5px 10px; height:35px;}
    .search-table-outter { overflow-x: scroll; }
th, td { min-width: 200px; }


</style>

Java: set timeout on a certain block of code?

I faced a similar kind of issue where my task was to push a message to SQS within a particular timeout. I used the trivial logic of executing it via another thread and waiting on its future object by specifying the timeout. This would give me a TIMEOUT exception in case of timeouts.

final Future<ISendMessageResult> future = 
timeoutHelperThreadPool.getExecutor().submit(() -> {
  return getQueueStore().sendMessage(request).get();
});
try {
  sendMessageResult = future.get(200, TimeUnit.MILLISECONDS);
  logger.info("SQS_PUSH_SUCCESSFUL");
  return true;

} catch (final TimeoutException e) {
  logger.error("SQS_PUSH_TIMEOUT_EXCEPTION");
}

But there are cases where you can't stop the code being executed by another thread and you get true negatives in that case.

For example - In my case, my request reached SQS and while the message was being pushed, my code logic encountered the specified timeout. Now in reality my message was pushed into the Queue but my main thread assumed it to be failed because of the TIMEOUT exception. This is a type of problem which can be avoided rather than being solved. Like in my case I avoided it by providing a timeout which would suffice in nearly all of the cases.

If the code you want to interrupt is within you application and is not something like an API call then you can simply use

future.cancel(true)

However do remember that java docs says that it does guarantee that the execution will be blocked.

"Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled,or could not be cancelled for some other reason. If successful,and this task has not started when cancel is called,this task should never run. If the task has already started,then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted inan attempt to stop the task."

How to calculate date difference in JavaScript?

<html lang="en">
<head>
<script>
function getDateDiff(time1, time2) {
  var str1= time1.split('/');
  var str2= time2.split('/');

  //                yyyy   , mm       , dd
  var t1 = new Date(str1[2], str1[0]-1, str1[1]);
  var t2 = new Date(str2[2], str2[0]-1, str2[1]);

  var diffMS = t1 - t2;    
  console.log(diffMS + ' ms');

  var diffS = diffMS / 1000;    
  console.log(diffS + ' ');

  var diffM = diffS / 60;
  console.log(diffM + ' minutes');

  var diffH = diffM / 60;
  console.log(diffH + ' hours');

  var diffD = diffH / 24;
  console.log(diffD + ' days');
  alert(diffD);
}

//alert(getDateDiff('10/18/2013','10/14/2013'));
</script>
</head>
<body>
  <input type="button" 
       onclick="getDateDiff('10/18/2013','10/14/2013')" 
       value="clickHere()" />

</body>
</html>

How to add external JS scripts to VueJS Components

Simplest solution is to add the script in the index.html file of your vue-project

index.html:

 <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <title>vue-webpack</title>
      </head>
      <body>
        <div id="app"></div>
        <!-- start Mixpanel --><script type="text/javascript">(function(c,a){if(!a.__SV){var b=window;try{var d,m,j,k=b.location,f=k.hash;d=function(a,b){return(m=a.match(RegExp(b+"=([^&]*)")))?m[1]:null};f&&d(f,"state")&&(j=JSON.parse(decodeURIComponent(d(f,"state"))),"mpeditor"===j.action&&(b.sessionStorage.setItem("_mpcehash",f),history.replaceState(j.desiredHash||"",c.title,k.pathname+k.search)))}catch(n){}var l,h;window.mixpanel=a;a._i=[];a.init=function(b,d,g){function c(b,i){var a=i.split(".");2==a.length&&(b=b[a[0]],i=a[1]);b[i]=function(){b.push([i].concat(Array.prototype.slice.call(arguments,
    0)))}}var e=a;"undefined"!==typeof g?e=a[g]=[]:g="mixpanel";e.people=e.people||[];e.toString=function(b){var a="mixpanel";"mixpanel"!==g&&(a+="."+g);b||(a+=" (stub)");return a};e.people.toString=function(){return e.toString(1)+".people (stub)"};l="disable time_event track track_pageview track_links track_forms track_with_groups add_group set_group remove_group register register_once alias unregister identify name_tag set_config reset opt_in_tracking opt_out_tracking has_opted_in_tracking has_opted_out_tracking clear_opt_in_out_tracking people.set people.set_once people.unset people.increment people.append people.union people.track_charge people.clear_charges people.delete_user people.remove".split(" ");
    for(h=0;h<l.length;h++)c(e,l[h]);var f="set set_once union unset remove delete".split(" ");e.get_group=function(){function a(c){b[c]=function(){call2_args=arguments;call2=[c].concat(Array.prototype.slice.call(call2_args,0));e.push([d,call2])}}for(var b={},d=["get_group"].concat(Array.prototype.slice.call(arguments,0)),c=0;c<f.length;c++)a(f[c]);return b};a._i.push([b,d,g])};a.__SV=1.2;b=c.createElement("script");b.type="text/javascript";b.async=!0;b.src="undefined"!==typeof MIXPANEL_CUSTOM_LIB_URL?
    MIXPANEL_CUSTOM_LIB_URL:"file:"===c.location.protocol&&"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js".match(/^\/\//)?"https://cdn.mxpnl.com/libs/mixpanel-2-latest.min.js":"//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js";d=c.getElementsByTagName("script")[0];d.parentNode.insertBefore(b,d)}})(document,window.mixpanel||[]);
    mixpanel.init("xyz");</script><!-- end Mixpanel -->
        <script src="/dist/build.js"></script>
      </body>
    </html>

Get a particular cell value from HTML table using JavaScript

Make a javascript function

function addSampleTextInInputBox(message) {
    //set value in input box
    document.getElementById('textInput').value = message + "";
    //or show an alert
    //window.alert(message);
}

Then simply call in your table row button click

<td class="center">
    <a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
        <span class="fa fa-plus"></span>
    </a>
</td>

iOS 7 status bar back to iOS 6 default style in iPhone app?

This might be too late to share, but I have something to contribute which might help someone, I was trying to sub-class the UINavigationBar and wanted to make it look like ios 6 with black status bar and status bar text in white.

Here is what I found working for that

        self.navigationController?.navigationBar.clipsToBounds = true
        self.navigationController?.navigationBar.translucent = false
        self.navigationController?.navigationBar.barStyle = .Black
        self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()

It made my status bar background black, status bar text white and navigation bar's color white.

iOS 9.3, XCode 7.3.1

Python 2,3 Convert Integer to "bytes" Cleanly

Converting an int to a byte in Python 3:

    n = 5    
    bytes( [n] )

>>> b'\x05'

;) guess that'll be better than messing around with strings

source: http://docs.python.org/3/library/stdtypes.html#binaryseq

How does inline Javascript (in HTML) work?

Try this in the console:

var div = document.createElement('div');

div.setAttribute('onclick', 'alert(event)');

div.onclick

In Chrome, it shows this:

function onclick(event) {
  alert(event)
}

...and the non-standard name property of div.onclick is "onclick".

So, whether or not this is anonymous depends your definition of "anonymous." Compare with something like var foo = new Function(), where foo.name is an empty string, and foo.toString() will produce something like

function anonymous() {

}

How to start jenkins on different port rather than 8080 using command prompt in Windows?

For the benefit of Linux users who find themselves here: I found /etc/sysconfig/jenkins has a JENKINS_PORT="8080", which you should probably change too.

How to change package name in android studio?

First click once on your package and then click setting icon on Android Studio.

Close/Unselect Compact Empty Middle Packages

Then, right click your package and rename it.

Thats all.

enter image description here

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

You should execute the next query:

GRANT ALL ON TABLE mytable TO myuser;

Or if your error is in a view then maybe the table does not have permission, so you should execute the next query:

GRANT ALL ON TABLE tbm_grupo TO myuser;

change text of button and disable button in iOS

If somebody, who is looking for a solution in Swift, landed here, it would be:

myButton.isEnabled = false // disables
myButton.setTitle("myTitle", for: .normal) // sets text

Documentation: isEnabled, setTitle.

Older code:

myButton.enabled = false // disables
myButton.setTitle("myTitle", forState: UIControlState.Normal) // sets text

Best way to get whole number part of a Decimal number

   Public Function getWholeNumber(number As Decimal) As Integer
    Dim round = Math.Round(number, 0)
    If round > number Then
        Return round - 1
    Else
        Return round
    End If
End Function

Nginx: Job for nginx.service failed because the control process exited

In my case, nginx was not able to open the log file which is located here /var/log/nginx/error.log

This was because I had deleted the log directory to free up space in root (which turned out to be stupid)

I then created a log folder in var and an nginx folder in log.

Then simply run sudo service nginx start

How can I convert a DateTime to an int?

Do you want an 'int' that looks like 20110425171213? In which case you'd be better off ToString with the appropriate format (something like 'yyyyMMddHHmmss') and then casting the string to an integer (or a long, unsigned int as it will be way more than 32 bits).

If you want an actual numeric value (the number of seconds since the year 0) then that's a very different calculation, e.g.

result = second
result += minute * 60
result += hour * 60 * 60
result += day * 60 * 60 * 24 

etc.

But you'd be better off using Ticks.

JQuery Number Formatting

I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. Could be usefull.

number_format = function (number, decimals, dec_point, thousands_sep) {
        number = number.toFixed(decimals);

        var nstr = number.toString();
        nstr += '';
        x = nstr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? dec_point + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

        return x1 + x2;
    }

For example:

var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56

Center Contents of Bootstrap row container

With Bootstrap 4, there is a css class specifically for this. The below will center row content:

<div class="row justify-content-center">
  ...inner divs and content...
</div>

See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

How to add two edit text fields in an alert dialog

Use these lines in the code, because the textEntryView is the parent of username edittext and password edittext.

    final EditText input1 = (EditText) textEntryView .findViewById(R.id.username); 
    final EditText input2 = (EditText) textEntryView .findViewById(R.id.password); 

SQLDataReader Row Count

Maybe you can try this: though please note - This pulls the column count, not the row count

 using (SqlDataReader reader = command.ExecuteReader())
 {
     while (reader.Read())
     {
         int count = reader.VisibleFieldCount;
         Console.WriteLine(count);
     }
 }

How to run TestNG from command line

After gone throug the various post, this worked fine for me doing on IntelliJ Idea:

java -cp "./lib/*;Path to your test.class"  org.testng.TestNG testng.xml

Here is my directory structure:

/lib
  -- all jar including testng.jar
/out
  --/production/Example1/test.class
/src
 -- test.java
testing.xml

So execute by this command:

java -cp "./lib/*;C:\Users\xyz\IdeaProjects\Example1\out\production\Example1" org.testng.TestNG testng.xml

My project directory Example1 is in the path:

C:\Users\xyz\IdeaProjects\

Kotlin Android start new Activity

This is because your Page2 class doesn't have a companion object which is similar to static in Java so to use your class. To pass your class as an argument to Intent, you will have to do something like this

val changePage = Intent(this, Page2::class.java)

Get keys of a Typescript interface as array of strings

The following requires you to list the keys on your own, but at least TypeScript will enforce IUserProfile and IUserProfileKeys have the exact same keys (Required<T> was added in TypeScript 2.8):

export interface IUserProfile  {
  id: string;
  name: string;
};
type KeysEnum<T> = { [P in keyof Required<T>]: true };
const IUserProfileKeys: KeysEnum<IUserProfile> = {
  id: true,
  name: true,
};

How to redraw DataTable with new data

The following worked really well for me. I needed to redraw the datatable with a different subset of the data based on a parameter.

table.ajax.url('NewDataUrl?parameter=' + param).load();

If your data is static, then use this:

table.ajax.url('NewDataUrl').load();

Regex to replace everything except numbers and a decimal point

Check the link Regular Expression Demo

use the below reg exp

[a-z] + [^0-9\s.]+|.(?!\d)

React Native TextInput that only accepts numeric characters

I had the same problem in iOS, using the onChangeText event to update the value of the text typed by the user I was not being able to update the value of the TextInput, so the user would still see the non numeric characters that he typed.

This was because, when a non numeric character was pressed the state would not change since this.setState would be using the same number (the number that remained after removing the non numeric characters) and then the TextInput would not re render.

The only way I found to solve this was to use the keyPress event which happens before the onChangeText event, and in it, use setState to change the value of the state to another, completely different, forcing the re render when the onChangeText event was called. Not very happy with this but it worked.

Find a row in dataGridView based on column and value

Try this:

        string searchValue = textBox3.Text;
        int rowIndex = -1;

        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        try
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                if (row.Cells["peseneli"].Value.ToString().Equals(searchValue))
                {
                    rowIndex = row.Index;
                    dataGridView1.CurrentCell = dataGridView1.Rows[rowIndex].Cells[0];
                    dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = true;

                    break;
                }
            }
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }

How to debug external class library projects in visual studio?

Assume the path of

Project A

C:\Projects\ProjectA

Project B

C:\Projects\ProjectB

and the dll of ProjectB is in

C:\Projects\ProjectB\bin\Debug\

To debug into ProjectB from ProjectA, do the following

  1. Copy B's dll with dll's .PDB to the ProjectA's compiling directory.
  2. Now debug ProjectA. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.

NOTE : DO NOT MISS TO COPY THE .PDB FILE

Cannot read property 'style' of undefined -- Uncaught Type Error

It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

_x000D_
_x000D_
window.onload = function() {_x000D_
_x000D_
  if (window.location.href.indexOf("test") <= -1) {_x000D_
    var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
    search_span[0].style.color = "blue";_x000D_
    search_span[0].style.fontWeight = "bold";_x000D_
    search_span[0].style.fontSize = "40px";_x000D_
_x000D_
  }_x000D_
_x000D_
}
_x000D_
<h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
_x000D_
_x000D_
_x000D_

What is the difference between CSS and SCSS?

css has variables as well. You can use them like this:

--primaryColor: #ffffff;
--width: 800px;

body {
    width: var(--width);
    color: var(--primaryColor);
}
.content{
    width: var(--width);
    background: var(--primaryColor);
}

.append(), prepend(), .after() and .before()

To try and answer your main question:

why would you use .append() rather then .after() or vice verses?

When you are manipulating the DOM with jquery the methods you use depend on the result you want and a frequent use is to replace content.

In replacing content you want to .remove() the content and replace it with new content. If you .remove() the existing tag and then try to use .append() it won't work because the tag itself has been removed, whereas if you use .after(), the new content is added 'outside' the (now removed) tag and isn't affected by the previous .remove().

SQL to LINQ Tool

Bill Horst's - Converting SQL to LINQ is a very good resource for this task (as well as LINQPad).

LINQ Tools has a decent list of tools as well but I do not believe there is anything else out there that can do what Linqer did.


Generally speaking, LINQ is a higher-level querying language than SQL which can cause translation loss when trying to convert SQL to LINQ. For one, LINQ emits shaped results and SQL flat result sets. The issue here is that an automatic translation from SQL to LINQ will often have to perform more transliteration than translation - generating examples of how NOT to write LINQ queries. For this reason, there are few (if any) tools that will be able to reliably convert SQL to LINQ. Analogous to learning C# 4 by first converting VB6 to C# 4 and then studying the resulting conversion.

Get file content from URL?

Don't forget: to get HTTPS contents, your OPENSSL extension should be enabled in your php.ini. (how to get contents of site use HTTPS)

PHP Fatal error: Class 'PDO' not found

Its a Little Late but I found the same problem and i fixed it by a "\" in front of PDO

public function enabled() {
    return in_array('mysql', \PDO::getAvailableDrivers());
}

How to switch Python versions in Terminal?

As Inian suggested, you should alias python to point to python 3. It is very easy to do, and very easy to switchback, personally i have an alias setup for p2=python2 and p3=python3 as well to save on keystrokes. Read here for more information: How do I create a Bash alias?

Here is an example of doing so for python:

alias python=python3

Like so:

$ python --version
Python 2.7.6
$ python3 --version
Python 3.4.3
$ alias python=python3
$ python --version
Python 3.4.3

See here for the original: https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3

Graphviz's executables are not found (Python 3.4)

I solved it installing directly from https://graphviz.gitlab.io/_pages/Download/Download_windows.html and including in windows path:

C:\Program Files (x86)\Graphviz2.38\bin

C:\Program Files (x86)\Graphviz2.38

After I restart windows

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

The two calls have different meanings that have nothing to do with performance; the fact that it speeds up the execution time is (or might be) just a side effect. You should understand what each of them does and not blindly include them in every program because they look like an optimization.

ios_base::sync_with_stdio(false);

This disables the synchronization between the C and C++ standard streams. By default, all standard streams are synchronized, which in practice allows you to mix C- and C++-style I/O and get sensible and expected results. If you disable the synchronization, then C++ streams are allowed to have their own independent buffers, which makes mixing C- and C++-style I/O an adventure.

Also keep in mind that synchronized C++ streams are thread-safe (output from different threads may interleave, but you get no data races).

cin.tie(NULL);

This unties cin from cout. Tied streams ensure that one stream is flushed automatically before each I/O operation on the other stream.

By default cin is tied to cout to ensure a sensible user interaction. For example:

std::cout << "Enter name:";
std::cin >> name;

If cin and cout are tied, you can expect the output to be flushed (i.e., visible on the console) before the program prompts input from the user. If you untie the streams, the program might block waiting for the user to enter their name but the "Enter name" message is not yet visible (because cout is buffered by default, output is flushed/displayed on the console only on demand or when the buffer is full).

So if you untie cin from cout, you must make sure to flush cout manually every time you want to display something before expecting input on cin.

In conclusion, know what each of them does, understand the consequences, and then decide if you really want or need the possible side effect of speed improvement.

SQLAlchemy: What's the difference between flush() and commit()?

Use flush when you need to write, for example to get a primary key ID from an autoincrementing counter.

john=Person(name='John Smith', parent=None)
session.add(john)
session.flush()

son=Person(name='Bill Smith', parent=john.id)

Without flushing, john would never get an ID from the DB and so couldn't represent the parent/child relationship in code.

Like others have said, without commit() none of this will be permanently persisted to DB.

Python pandas: how to specify data types when reading an Excel file?

In case if you are not aware of the number and name of columns in dataframe then this method can be handy:

column_list = []
df_column = pd.read_excel(file_name, 'Sheet1').columns
for i in df_column:
    column_list.append(i)
converter = {col: str for col in column_list} 
df_actual = pd.read_excel(file_name, converters=converter)

where column_list is the list of your column names.

NavigationBar bar, tint, and title text color in iOS 8

Swift 4

override func viewDidLoad() {
    super.viewDidLoad()

    navigationController?.navigationBar.barTintColor = UIColor.orange
    navigationController?.navigationBar.tintColor = UIColor.white
    navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
}

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

In addition to @fareed namrouti's answer,

This should be used if the image has to be browsed from a file input element

<input type="file" name="file" id="file-input"><br/>
image after transform: <br/>
<div id="container"></div>

<script>
    document.getElementById('file-input').onchange = function (e) {
        var image = e.target.files[0];
        window.loadImage(image, function (img) {
            if (img.type === "error") {
                console.log("couldn't load image:", img);
            } else {
                window.EXIF.getData(image, function () {
                    console.log("load image done!");
                    var orientation = window.EXIF.getTag(this, "Orientation");
                    var canvas = window.loadImage.scale(img,
                        {orientation: orientation || 0, canvas: true, maxWidth: 200});
                    document.getElementById("container").appendChild(canvas);
                    // or using jquery $("#container").append(canvas);
                });
            }
        });
    };
</script>

How to correctly close a feature branch in Mercurial?

imho there are two cases for branches that were forgot to close

Case 1: branch was not merged into default

in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.

hg up myBranch
hg commit --close-branch

Case 2: branch was merged into default

This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.

in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!

hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch

Hope this helps future readers.

Using local makefile for CLion instead of CMake

While this is one of the most voted feature requests, there is one plugin available, by Victor Kropp, that adds support to makefiles:

Makefile support plugin for IntelliJ IDEA

Install

You can install directly from the official repository:

Settings > Plugins > search for makefile > Search in repositories > Install > Restart

Use

There are at least three different ways to run:

  1. Right click on a makefile and select Run
  2. Have the makefile open in the editor, put the cursor over one target (anywhere on the line), hit alt + enter, then select make target
  3. Hit ctrl/cmd + shift + F10 on a target (although this one didn't work for me on a mac).

It opens a pane named Run target with the output.

Using sudo with Python script

  • Use -S option in the sudo command which tells to read the password from 'stdin' instead of the terminal device.

  • Tell Popen to read stdin from PIPE.

  • Send the Password to the stdin PIPE of the process by using it as an argument to communicate method. Do not forget to add a new line character, '\n', at the end of the password.

sp = Popen(cmd , shell=True, stdin=PIPE)
out, err = sp.communicate(_user_pass+'\n')   

How to get a cross-origin resource sharing (CORS) post request working

I had the exact same issue where jquery ajax only gave me cors issues on post requests where get requests worked fine - I tired everything above with no results. I had the correct headers in my server etc. Changing over to use XMLHTTPRequest instead of jquery fixed my issue immediately. No matter which version of jquery I used it didn't fix it. Fetch also works without issues if you don't need backward browser compatibility.

        var xhr = new XMLHttpRequest()
        xhr.open('POST', 'https://mywebsite.com', true)
        xhr.withCredentials = true
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 2) {// do something}
        }
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.send(json)

Hopefully this helps anyone else with the same issues.

OS X Framework Library not loaded: 'Image not found'

I think there is no fixed way to solve this problem since it might be caused by different reason. I also had this problem last week, I don't know when and exactly what cause this problem, only when I run it on simulator with Xcode or try to install it onto the phone, then it reports such kind of error, But when I run it with react-native run-ios with terminal, there is no problem.

I checked all the ways posted on the internet, like renew certificate, change settings in Xcode (all of ways mentions above), actually all of settings in Xcode were already set as it requested before, none of ways works for me. Until this morning when I delete the pods and reinstall, the error finally gonna after a week. If you are also using cocoapod and then error was just show up without any specific reason, maybe you can try my way.

  1. Check my cocoapods version.
  2. Update it if there is new version available.
  3. Go to your project folder, delete your Podfile.lock , Pods file, project xcworkspace.
  4. Run pod install

Selecting last element in JavaScript array

Underscore and Lodash have the _.last(Array) method, that returns the last element in an Array. They both work about the same

_.last([5, 4, 3, 2, 1]);
=> 1

Ramda also has a _.last function

R.last(['fi', 'fo', 'fum']); //=> 'fum'

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Android: long click on a button -> perform actions

Change return false; to return true; in longClickListener

You long click the button, if it returns true then it does the work. If it returns false then it does it's work and also calls the short click and then the onClick also works.

Fake "click" to activate an onclick method

If you're using JQuery you can do:

$('#elementid').click();

HTML.ActionLink method

You might want to look at the RouteLink() method.That one lets you specify everything (except the link text and route name) via a dictionary.

Javascript: open new page in same window

try this it worked for me in ie 7 and ie 8

 $(this).click(function (j) {
            var href = ($(this).attr('href'));
            window.location = href;
            return true;

Copy a git repo without history

#!/bin/bash
set -e

# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx

repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git

echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir

echo "CD"
cd ./$dir

echo "Remove GIT"
rm -rf .git

echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url

echo "Push..."
git push -u origin master

Java way to check if a string is palindrome

import java.util.Scanner;

public class FindAllPalindromes {
static String longestPalindrome;
public String oldPalindrome="";
static int longest;

public void allSubstrings(String s){        
    for(int i=0;i<s.length();i++){
        for(int j=1;j<=s.length()-i;j++){
            String subString=s.substring(i, i+j);  
            palindrome(subString);             
        }
    }
        }   
public void palindrome(String sub){
    System.out.println("String to b checked is "+sub);
    StringBuilder sb=new StringBuilder();
    sb.append(sub);     // append string to string builder 
    sb.reverse();        
    if(sub.equals(sb.toString())){                        // palindrome condition 
        System.out.println("the given String :"+sub+" is a palindrome");
        longestPalindrome(sub);
    }
    else{
        System.out.println("the string "+sub+"iss not a palindrome");
    }
        }
public void longestPalindrome(String s){
            if(s.length()>longest){                 
        longest=s.length();
        longestPalindrome=s;

    }
    else if (s.length()==longest){    
        oldPalindrome=longestPalindrome;
        longestPalindrome=s;

    }




}

public static void main(String[] args) {
FindAllPalindromes fp=new FindAllPalindromes();

    Scanner sc=new Scanner(System.in);    
    System.out.println("Enter the String ::");
    String s=sc.nextLine(); 
    fp.allSubstrings(s);      
    sc.close();
    if(fp.oldPalindrome.length()>0){
    System.out.println(longestPalindrome+"and"+fp.oldPalindrome+":is the longest palindrome");  
    }
    else{
        System.out.println(longestPalindrome+":is the longest palindrome`````");
    }}
}

onclick go full screen

I tried other answers on this question, and there are mistakes with the different browser APIs, particularly Fullscreen vs FullScreen. Here is my code that works with the major browsers (as of Q1 2019) and should continue to work as they standardize.

function fullScreenTgl() {
    let doc=document,elm=doc.documentElement;
    if      (elm.requestFullscreen      ) { (!doc.fullscreenElement   ? elm.requestFullscreen()       : doc.exitFullscreen()        ) }
    else if (elm.mozRequestFullScreen   ) { (!doc.mozFullScreen       ? elm.mozRequestFullScreen()    : doc.mozCancelFullScreen()   ) }
    else if (elm.msRequestFullscreen    ) { (!doc.msFullscreenElement ? elm.msRequestFullscreen()     : doc.msExitFullscreen()      ) }
    else if (elm.webkitRequestFullscreen) { (!doc.webkitIsFullscreen  ? elm.webkitRequestFullscreen() : doc.webkitCancelFullscreen()) }
    else                                  { console.log("Fullscreen support not detected.");                                          }
    }

Get day of week in SQL Server 2005/2008

With SQL Server 2012 and onward you can use the FORMAT function

SELECT FORMAT(GETDATE(), 'dddd')

What are the rules for casting pointers in C?

char c = '5'

A char (1 byte) is allocated on stack at address 0x12345678.

char *d = &c;

You obtain the address of c and store it in d, so d = 0x12345678.

int *e = (int*)d;

You force the compiler to assume that 0x12345678 points to an int, but an int is not just one byte (sizeof(char) != sizeof(int)). It may be 4 or 8 bytes according to the architecture or even other values.

So when you print the value of the pointer, the integer is considered by taking the first byte (that was c) and other consecutive bytes which are on stack and that are just garbage for your intent.

The remote certificate is invalid according to the validation procedure

Try put this before send e-mail

ServicePointManager.ServerCertificateValidationCallback = 
        delegate(object s, X509Certificate certificate, X509Chain chain,
        SslPolicyErrors sslPolicyErrors) { return true; };

Remenber to add the using libs!

Execute and get the output of a shell command in node.js

You can use the util library that comes with nodejs to get a promise from the exec command and can use that output as you need. Use restructuring to store the stdout and stderr in variables.

_x000D_
_x000D_
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const {
    stdout,
    stderr
  } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();
_x000D_
_x000D_
_x000D_

Business logic in MVC

Fist of all:
I believe that you are mixing up the MVC pattern and n-tier-based design principles.

Using an MVC approach does not mean that you shouldn't layer your application.
It might help if you see MVC more like an extension of the presentation layer.

If you put non-presentation code inside the MVC pattern you might very soon end up in a complicated design.
Therefore I would suggest that you put your business logic into a separate business layer.

Just have a look at this: Wikipedia article about multitier architecture

It says:

Today, MVC and similar model-view-presenter (MVP) are Separation of Concerns design patterns that apply exclusively to the presentation layer of a larger system.

Anyway ... when talking about an enterprise web application the calls from the UI to the business logic layer should be placed inside the (presentation) controller.

That is because the controller actually handles the calls to a specific resource, queries the data by making calls to the business logic and links the data (model) to the appropriate view.

Mud told you that the business rules go into the model.
That is also true, but he mixed up the (presentation) model (the 'M' in MVC) and the data layer model of a tier-based application design.
So it is valid to place your database related business rules in the model (data layer) of your application.
But you should not place them in the model of your MVC-structured presentation layer as this only applies to a specific UI.

This technique is independent of whether you use a domain driven design or a transaction script based approach.

Let me visualize that for you:


Presentation layer: Model - View - Controller


Business layer: Domain logic - Application logic


Data layer: Data repositories - Data access layer


The model that you see above means that you have an application that uses MVC, DDD and a database-independed data layer.
This is a common approach to design a larger enterprise web application.

But you can also shrink it down to use a simple non-DDD business layer (a business layer without domain logic) and a simple data layer that writes directly to a specific database.
You could even drop the whole data-layer and access the database directly from the business layer, though I do not recommend it.

Thats' the trick...I hope this helps...

[Note:] You should also be aware of the fact that nowadays there is more than just one "model" in an application. Commonly, each layer of an application has it's own model. The model of the presentation layer is view specific but often independent of the used controls. The business layer can also have a model, called the "domain-model". This is typically the case when you decide to take a domain-driven approach. This "domain-model" contains of data as well as business logic (the main logic of your program) and is usually independent of the presentation layer. The presentation layer usually calls the business layer on a certain "event" (button pressed etc.) to read data from or write data to the data layer. The data layer might also have it's own model, which is typically database related. It often contains a set of entity classes as well as data-access-objects (DAOs).

The question is: how does this fit into the MVC concept?

Answer -> It doesn't!
Well - it kinda does, but not completely.
This is because MVC is an approach that was developed in the late 1970's for the Smalltalk-80 programming language. At that time GUIs and personal computers were quite uncommon and the world wide web was not even invented! Most of today's programming languages and IDEs were developed in the 1990s. At that time computers and user interfaces were completely different from those in the 1970s.
You should keep that in mind when you talk about MVC.
Martin Fowler has written a very good article about MVC, MVP and today's GUIs.

Why ModelState.IsValid always return false in mvc

As Brad Wilson states in his answer here:

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

Try using :-

if (!ModelState.IsValid)
{
    var errors = ModelState.SelectMany(x => x.Value.Errors.Select(z => z.Exception));

    // Breakpoint, Log or examine the list with Exceptions.
}

If it helps catching you the error. Courtesy this and this

Repeat a task with a time delay?

You should use Handler's postDelayed function for this purpose. It will run your code with specified delay on the main UI thread, so you will be able to update UI controls.

private int mInterval = 5000; // 5 seconds by default, can be changed later
private Handler mHandler;

@Override
protected void onCreate(Bundle bundle) {

    // your code here

    mHandler = new Handler();
    startRepeatingTask();
}

@Override
public void onDestroy() {
    super.onDestroy();
    stopRepeatingTask();
}

Runnable mStatusChecker = new Runnable() {
    @Override 
    public void run() {
          try {
               updateStatus(); //this function can change value of mInterval.
          } finally {
               // 100% guarantee that this always happens, even if
               // your update method throws an exception
               mHandler.postDelayed(mStatusChecker, mInterval);
          }
    }
};

void startRepeatingTask() {
    mStatusChecker.run(); 
}

void stopRepeatingTask() {
    mHandler.removeCallbacks(mStatusChecker);
}

Default FirebaseApp is not initialized

As mentioned by @PSIXO in a comment, this might be the problem with the dependency version of google-services. For me changing,

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.1.0'
    }
}

to

buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

worked.There might be some problem with 4.1.0 version. Because I wasted many hours on this, I thought to write this as an answer.

How to get last key in an array?

Try this one with array_reverse().

 $arr = array(
     'first' => 01,
     'second' => 10,
     'third' => 20, 
 );  
 $key = key(array_reverse($arr));
 var_dump($key);

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

Bootstrap - Uncaught TypeError: Cannot read property 'fn' of undefined

//Call .noConflict() to restore JQuery reference.

jQuery.noConflict(); OR  $.noConflict();

//Do something with jQuery.

jQuery( "div.class" ).hide(); OR $( "div.class" ).show();

Android: Storing username and password?

These are ranked in order of difficulty to break your hidden info.

  1. Store in cleartext

  2. Store encrypted using a symmetric key

  3. Using the Android Keystore

  4. Store encrypted using asymmetric keys

source: Where is the best place to store a password in your Android app

The Keystore itself is encrypted using the user’s own lockscreen pin/password, hence, when the device screen is locked the Keystore is unavailable. Keep this in mind if you have a background service that could need to access your application secrets.

source: Simple use the Android Keystore to store passwords and other sensitive information

Create a File object in memory from a string in Java

The File class represents the "idea" of a file, not an actual handle to use for I/O. This is why the File class has a .exists() method, to tell you if the file exists or not. (How can you have a File object that doesn't exist?)

By contrast, constructing a new FileInputStream(new File("/my/file")) gives you an actual stream to read bytes from.

Ascending and Descending Number Order in java

int arr[] = { 12, 13, 54, 16, 25, 8, 78 };

for (int i = 0; i < arr.length; i++) {
    Arrays.sort(arr);
    System.out.println(arr[i]);
}

Count a list of cells with the same background color

I just created this and it looks easier. You get these 2 functions:

=GetColorIndex(E5)  <- returns color number for the cell

from (cell)

=CountColorIndexInRange(C7:C24,14) <- returns count of cells C7:C24 with color 14

from (range of cells, color number you want to count)

example shows percent of cells with color 14

=ROUND(CountColorIndexInRange(C7:C24,14)/18, 4 )

Create these 2 VBA functions in a Module (hit Alt-F11)

open + folders. double-click on Module1

Just paste this text below in, then close the module window (it must save it then):

Function GetColorIndex(Cell As Range)
  GetColorIndex = Cell.Interior.ColorIndex
End Function

Function CountColorIndexInRange(Rng As Range, TestColor As Long)
  Dim cnt
  Dim cl As Range
  cnt = 0

  For Each cl In Rng
    If GetColorIndex(cl) = TestColor Then
      Rem Debug.Print ">" & TestColor & "<"
      cnt = cnt + 1
    End If
  Next

  CountColorIndexInRange = cnt

End Function

How to assign the output of a command to a Makefile variable

Beware of recipes like this

target:
    MY_ID=$(GENERATE_ID);
    echo $MY_ID;

It does two things wrong. The first line in the recipe is executed in a separate shell instance from the second line. The variable is lost in the meantime. Second thing wrong is that the $ is not escaped.

target:
    MY_ID=$(GENERATE_ID); \
    echo $$MY_ID;

Both problems have been fixed and the variable is useable. The backslash combines both lines to run in one single shell, hence the setting of the variable and the reading of the variable afterwords, works.

I realize the original post said how to get the results of a shell command into a MAKE variable, and this answer shows how to get it into a shell variable. But other readers may benefit.

One final improvement, if the consumer expects an "environment variable" to be set, then you have to export it.

my_shell_script
    echo $MY_ID

would need this in the makefile

target:
    export MY_ID=$(GENERATE_ID); \
    ./my_shell_script;

Hope that helps someone. In general, one should avoid doing any real work outside of recipes, because if someone use the makefile with '--dry-run' option, to only SEE what it will do, it won't have any undesirable side effects. Every $(shell) call is evaluated at compile time and some real work could accidentally be done. Better to leave the real work, like generating ids, to the inside of the recipes when possible.

Error in plot.window(...) : need finite 'xlim' values

I had the same problem. I solve it when I convert string to factor. In your case, check the class of variable and check if they are numeric and 'train and test' should be factor.

What's in an Eclipse .classpath/.project file?

.project

When a project is created in the workspace, a project description file is automatically generated that describes the project. The sole purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace.

.classpath

Classpath specifies which Java source files and resource files in a project are considered by the Java builder and specifies how to find types outside of the project. The Java builder compiles the Java source files into the output folder and also copies the resources into it.

File Upload with Angular Material

html:
    <div class="upload">
        <span>upload image</span>
        <input
          #Image
          type="file"
          (change)="handleFileInput($event.target.files)"
          accept=".jpg,.svg,.png,.jpeg"
        />
        <img
          width="100%"
          height="100%"
          *ngIf="imageUrl"
          [src]="imageUrl"
          class="image"
        />
    </div>

app.component.ts

export class AppComponent {
  options = [{ value: "This is value 1", checked: true }];
  statuses = ["control"];

  // name = "Angular";//
  fileToUpload: any;
  imageUrl: any;
  handleFileInput(file: FileList) {
    this.fileToUpload = file.item(0);

    //Show image preview
    let reader = new FileReader();
    reader.onload = (event: any) => {
      this.imageUrl = event.target.result;
    };
    reader.readAsDataURL(this.fileToUpload);
  }
}

Code for download video from Youtube on Java, Android

3 steps:

  1. Check the sorce code (HTML) of YouTube, you'll get the link like this (http%253A%252F%252Fo-o.preferred.telemar-cnf1.v18.lscache6.c.youtube.com%252Fvideoplayback ...);

  2. Decode the url (remove the codes %2B,%25 etc), create a decoder with the codes: http://www.w3schools.com/tags/ref_urlencode.asp and use the function Uri.decode(url) to replace invalid escaped octets;

  3. Use the code to download stream:

    URL u = null;
    InputStream is = null;  
    
    try {
        u = new URL(url);
        is = u.openStream(); 
        HttpURLConnection huc = (HttpURLConnection)u.openConnection(); //to know the size of video
        int size = huc.getContentLength();                 
    
        if(huc != null) {
            String fileName = "FILE.mp4";
            String storagePath = Environment.getExternalStorageDirectory().toString();
            File f = new File(storagePath,fileName);
    
            FileOutputStream fos = new FileOutputStream(f);
            byte[] buffer = new byte[1024];
            int len1 = 0;
            if(is != null) {
                while ((len1 = is.read(buffer)) > 0) {
                    fos.write(buffer,0, len1);  
                }
            }
            if(fos != null) {
                fos.close();
            }
        }                       
    } catch (MalformedURLException mue) {
        mue.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        try {               
            if(is != null) {
                is.close();
            }
        } catch (IOException ioe) {
            // just going to ignore this one
        }
    }
    

That's all, most of stuff you'll find on the web!!!

How to get JSON object from Razor Model object in javascript

After use codevar json = @Html.Raw(Json.Encode(@Model.CollegeInformationlist));

You need use JSON.parse(JSON.stringify(json));

Single controller with multiple GET methods in ASP.NET Web API

None of the above examples worked for my personal needs. The below is what I ended up doing.

 public class ContainsConstraint : IHttpRouteConstraint
{       
    public string[] array { get; set; }
    public bool match { get; set; }

    /// <summary>
    /// Check if param contains any of values listed in array.
    /// </summary>
    /// <param name="param">The param to test.</param>
    /// <param name="array">The items to compare against.</param>
    /// <param name="match">Whether we are matching or NOT matching.</param>
    public ContainsConstraint(string[] array, bool match)
    {

        this.array = array;
        this.match = match;
    }

    public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)
    {
        if (values == null) // shouldn't ever hit this.                   
            return true;

        if (!values.ContainsKey(parameterName)) // make sure the parameter is there.
            return true;

        if (string.IsNullOrEmpty(values[parameterName].ToString())) // if the param key is empty in this case "action" add the method so it doesn't hit other methods like "GetStatus"
            values[parameterName] = request.Method.ToString();

        bool contains = array.Contains(values[parameterName]); // this is an extension but all we are doing here is check if string array contains value you can create exten like this or use LINQ or whatever u like.

        if (contains == match) // checking if we want it to match or we don't want it to match
            return true;
        return false;             

    }

To use the above in your route use:

config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}", new { action = RouteParameter.Optional, id = RouteParameter.Optional}, new { action = new ContainsConstraint( new string[] { "GET", "PUT", "DELETE", "POST" }, true) });

What happens is the constraint kind of fakes in the method so that this route will only match the default GET, POST, PUT and DELETE methods. The "true" there says we want to check for a match of the items in array. If it were false you'd be saying exclude those in the strYou can then use routes above this default method like:

config.Routes.MapHttpRoute("GetStatus", "{controller}/status/{status}", new { action = "GetStatus" });

In the above it is essentially looking for the following URL => http://www.domain.com/Account/Status/Active or something like that.

Beyond the above I'm not sure I'd get too crazy. At the end of the day it should be per resource. But I do see a need to map friendly urls for various reasons. I'm feeling pretty certain as Web Api evolves there will be some sort of provision. If time I'll build a more permanent solution and post.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

To isolate any set of bits, apply an AND mask.

If you want the last X bits of a value, there is a simple trick that can be used.

unsigned  mask;
mask = (1 << X) - 1;
lastXbits = value & mask;

If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

unsigned  mask;
mask = ((1 << X) - 1) << startBit;
isolatedXbits = value & mask;

Hope this helps.

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

zsh compinit: insecure directories

This works for my Mac since High Sierra update.

Remove the group write access:

sudo chmod g-w /usr/local/share/zsh/site-functions
sudo chmod g-w /usr/local/share/zsh

It’s best to keep the change limited to zsh directories.

Screenshot sizes for publishing android app on Google Play

At last! I got the answer to this, the size to edit it in photoshop is: 379x674

You are welcome

Append Char To String in C?

If Linux is your concern, the easiest way to append two strings:

char * append(char * string1, char * string2)
{
    char * result = NULL;
    asprintf(&result, "%s%s", string1, string2);
    return result;
}

This won't work with MS Visual C.

Note: you have to free() the memory returned by asprintf()

Python strptime() and timezones?

I recommend using python-dateutil. Its parser has been able to parse every date format I've thrown at it so far.

>>> from dateutil import parser
>>> parser.parse("Tue Jun 22 07:46:22 EST 2010")
datetime.datetime(2010, 6, 22, 7, 46, 22, tzinfo=tzlocal())
>>> parser.parse("Fri, 11 Nov 2011 03:18:09 -0400")
datetime.datetime(2011, 11, 11, 3, 18, 9, tzinfo=tzoffset(None, -14400))
>>> parser.parse("Sun")
datetime.datetime(2011, 12, 18, 0, 0)
>>> parser.parse("10-11-08")
datetime.datetime(2008, 10, 11, 0, 0)

and so on. No dealing with strptime() format nonsense... just throw a date at it and it Does The Right Thing.

Update: Oops. I missed in your original question that you mentioned that you used dateutil, sorry about that. But I hope this answer is still useful to other people who stumble across this question when they have date parsing questions and see the utility of that module.

g++ ld: symbol(s) not found for architecture x86_64

I had a similar warning/error/failure when I was simply trying to make an executable from two different object files (main.o and add.o). I was using the command:

gcc -o exec main.o add.o

But my program is a C++ program. Using the g++ compiler solved my issue:

g++ -o exec main.o add.o

I was always under the impression that gcc could figure these things out on its own. Apparently not. I hope this helps someone else searching for this error.

How to change the Content of a <textarea> with JavaScript

If it's jQuery...

$("#myText").val('');

or

document.getElementById('myText').value = '';

Reference: Text Area Object

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

how do I print an unsigned char as hex in c++ using ostream?

I think TrungTN and anon's answer is okay, but MartinStettner's way of implementing the hex() function is not really simple, and too dark, considering hex << (int)mychar is already a workaround.

here is my solution to make "<<" operator easier:

#include <sstream>
#include <iomanip>

string uchar2hex(unsigned char inchar)
{
  ostringstream oss (ostringstream::out);
  oss << setw(2) << setfill('0') << hex << (int)(inchar);
  return oss.str();
}

int main()
{
  unsigned char a = 131;
  std::cout << uchar2hex(a) << std::endl;
}

It's just not worthy implementing a stream operator :-)

Keyboard shortcut to change font size in Eclipse?

Here's a quicker way than multi-layer menus without resorting to plug-ins:

Use the Quick Access tool at the upper left corner.

Type in "font", then, from the list that drops down, click on the link for "Preferences->Colors and Fonts->General->Appearance".

One click replaces the 4 needed to get there through menus. I do it so often, my Quick Access tool pulls it up as a previous choice right at the top of the list so I can just type "font" with a tap on the enter key and Boom!, I'm there.

If you want a keyboard shortcut, Ctrl+3 sets the focus to the Quick Access tool. Better yet, this even automatically brings up a list with your previous choices. The last one you chose will be on top, in which case a simple Ctrl+3 followed by enter would bring you straight there! I use this all the time to make it bigger during long typing or reading sessions to ease eye strain, or to make it smaller if I need more text on the screen at one time to make it easier to find something.

It's not quite as nice as zooming with the scroll wheel or with a simple Ctrl+ or Ctrl-, but it's a lot better than navigating through the menus every time!

spacing between form fields

I would wrap your rows in labels

<form action="doit" id="doit" method="post">
    <label>
        Name
        <input id="name" name="name" type="text" />
    </label>
    <label>
        Phone number
        <input id="phone" name="phone" type="text" />
    </label>
    <label>
        Year
        <input id="year" name="year" type="text" />
    </label>
</form>

And use

label, input {
    display: block;
}

label {
    margin-bottom: 20px;
}

Don't use brs for spacing!

Demo: http://jsfiddle.net/D8W2Q/

Variable name as a string in Javascript

This works for basic expressions

const nameof = exp => exp.toString().match(/[.](\w+)/)[1];

Example

nameof(() => options.displaySize);

Snippet:

_x000D_
_x000D_
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };_x000D_
var myFirstName = 'Chuck';_x000D_
var varname = nameof(function () { return window.myFirstName; });_x000D_
console.log(varname);
_x000D_
_x000D_
_x000D_

How do I determine the current operating system with Node.js

const path = require('path');

if (path.sep === "\\") {
console.log("Windows");
} else {
console.log("Not Windows");
}

How to strip a specific word from a string?

Use str.replace.

>>> papa.replace('papa', '')
' is a good man'
>>> app.replace('papa', '')
'app is important'

Alternatively use re and use regular expressions. This will allow the removal of leading/trailing spaces.

>>> import re
>>> papa = 'papa is a good man'
>>> app = 'app is important'
>>> papa3 = 'papa is a papa, and papa'
>>>
>>> patt = re.compile('(\s*)papa(\s*)')
>>> patt.sub('\\1mama\\2', papa)
'mama is a good man'
>>> patt.sub('\\1mama\\2', papa3)
'mama is a mama, and mama'
>>> patt.sub('', papa3)
'is a, and'

How to search for an element in a golang slice

You can save the struct into a map by matching the struct Key and Value components to their fictive key and value parts on the map:

mapConfig := map[string]string{}
for _, v := range myconfig {
   mapConfig[v.Key] = v.Value
}

Then using the golang comma ok idiom you can test for the key presence:

if v, ok := mapConfig["key1"]; ok {
    fmt.Printf("%s exists", v)
}   

Lua - Current time in milliseconds

In standard C lua, no. You will have to settle for seconds, unless you are willing to modify the lua interpreter yourself to have os.time use the resolution you want. That may be unacceptable, however, if you are writing code for other people to run on their own and not something like a web application where you have full control of the environment.

Edit: another option is to write your own small DLL in C that extends lua with a new function that would give you the values you want, and require that dll be distributed with your code to whomever is going to be using it.

Could not load type 'XXX.Global'

Changing the address's port number (localhost:) worked for me :)

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

If you want to apply some condition on form submit then you can use this method

<form onsubmit="return checkEmpData();" method="post" action="process.html">
  <input type="text" border="0" name="submit" />
  <button value="submit">submit</button>
</form>

One thing always keep in mind that method and action attribute write after onsubmit attributes

javascript code

function checkEmpData()
{
  var a = 0;

  if(a != 0)
  {
    return confirm("Do you want to generate attendance?");
  }
   else
   {
      alert('Please Select Employee First');
      return false;
   }  
}

What is the C# version of VB.net's InputDialog?

Add reference to Microsoft.VisualBasic and use this function:

string response =  Microsoft.VisualBasic.Interaction.InputBox("What's 1+1?", "Title", "2", 0, 0);

The last 2 number is an X/Y position to display the input dialog.

Python None comparison: should I use "is" or ==?

is is generally preferred when comparing arbitrary objects to singletons like None because it is faster and more predictable. is always compares by object identity, whereas what == will do depends on the exact type of the operands and even on their ordering.

This recommendation is supported by PEP 8, which explicitly states that "comparisons to singletons like None should always be done with is or is not, never the equality operators."

Class method differences in Python: bound, unbound and static

When you call a class member, Python automatically uses a reference to the object as the first parameter. The variable self actually means nothing, it's just a coding convention. You could call it gargaloo if you wanted. That said, the call to method_two would raise a TypeError, because Python is automatically trying to pass a parameter (the reference to its parent object) to a method that was defined as having no parameters.

To actually make it work, you could append this to your class definition:

method_two = staticmethod(method_two)

or you could use the @staticmethod function decorator.

Using a dictionary to select function to execute

You are wasting your time:

  1. You are about to write a lot of useless code and introduce new bugs.
  2. To execute the function, your user will need to know the P1 name anyway.
  3. Etc., etc., etc.

Just put all your functions in the .py file:

# my_module.py

def f1():
    pass

def f2():
    pass

def f3():
    pass

And use them like this:

import my_module

my_module.f1()
my_module.f2()
my_module.f3()

or:

from my_module import f1
from my_module import f2
from my_module import f3

f1()
f2()
f3()

This should be enough for starters.

How do I convert a column of text URLs into active hyperlinks in Excel?

Thank you Cassiopeia for code. I change his code to work with local addresses and made little changes to his conditions. I removed following conditions:

  1. Change http:/ to file:///
  2. Removed all type of white space conditions
  3. Changed 10k cell range condition to 100k

Sub HyperAddForLocalLinks()
Dim CellsWithSpaces As String
    'Converts each text hyperlink selected into a working hyperlink
    Application.ScreenUpdating = False
    Dim NotPresent As Integer
    NotPresent = 0

    For Each xCell In Selection
        xCell.Formula = Trim(xCell.Formula)
            If InStr(xCell.Formula, "file:///") <> 0 Then
                Hyperstring = Trim(xCell.Formula)
            Else
                Hyperstring = "file:///" & Trim(xCell.Formula)
            End If

            ActiveSheet.Hyperlinks.Add Anchor:=xCell, Address:=Hyperstring

        i = i + 1
        If i = 100000 Then Exit Sub
Nextxcell:
      Next xCell
    Application.ScreenUpdating = True
End Sub

CORS error :Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response

If you don't want to install the cors library and instead want to fix your original code, the other step you are missing is that Access-Control-Allow-Origin:* is wrong. When passing Authentication tokens (e.g. JWT) then you must explicitly state every url that is calling your server. You can't use "*" when doing authentication tokens.