Programs & Examples On #Caf

CAF (Core Audio Format) is a container audio file format developed by Apple. CAF files can contain audio data of a variety of different formats and are not limited to 4GB in size. The format is used by certain Apple products (such as Apple Loops) and is supported on both Mac OS X and iOS platforms.

Flutter: RenderBox was not laid out

i

I used this code to fix the issue of displaying items in the horizontal list.

new Container(
      height: 20,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          ListView.builder(
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            itemCount: array.length,
            itemBuilder: (context, index){
              return array[index];
            },
          ),
        ],
      ),
    );

Flutter - The method was called on null

Because of your initialization wrong.

Don't do like this,

MethodName _methodName;

Do like this,

MethodName _methodName = MethodName();

How to scroll page in flutter

You can try CustomScrollView. Put your CustomScrollView inside Column Widget.

Just for example -

class App extends StatelessWidget {

 App({Key key}): super(key: key);

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(
          title: const Text('AppBar'),
      ),
      body: new Container(
          constraints: BoxConstraints.expand(),
          decoration: new BoxDecoration(
            image: new DecorationImage(
              alignment: Alignment.topLeft,
              image: new AssetImage('images/main-bg.png'),
              fit: BoxFit.cover,
            )
          ),
          child: new Column(
            children: <Widget>[               
              Expanded(
                child: new CustomScrollView(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: false,
                  slivers: <Widget>[
                    new SliverPadding(
                      padding: const EdgeInsets.symmetric(vertical: 0.0),
                      sliver: new SliverList(
                        delegate: new SliverChildBuilderDelegate(
                          (context, index) => new YourRowWidget(),
                          childCount: 5,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          )),
    );
  }
}

In above code I am displaying a list of items ( total 5) in CustomScrollView. YourRowWidget widget gets rendered 5 times as list item. Generally you should render each row based on some data.

You can remove decoration property of Container widget, it is just for providing background image.

Flutter : Vertically center column

You could use. mainAxisAlignment:MainAxisAlignment.center This will the material through the center in the column wise. `crossAxisAlignment: CrossAxisAlignment.center' This will align the items in the center in the row wise.

Container( alignment:Alignment.center, Child: Column () )

Simply use. Center ( Child: Column () ) or rap with Padding widget . And adjust the Padding such the the column children are in the center.

How to add image in Flutter

To use image in Flutter. Do these steps.

1. Create a Directory inside assets folder named images. As shown in figure belowenter image description here

2. Put your desired images to images folder.

3. Open pubpsec.yaml file . And add declare your images.Like:--enter image description here

4. Use this images in your code as.

  Card(
            elevation: 10,
              child: Container(
              decoration: BoxDecoration(
                color: Colors.orangeAccent,
              image: DecorationImage(
              image: AssetImage("assets/images/dropbox.png"),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
          ),
          ),
          child: Text("$index",style: TextStyle(color: Colors.red,fontSize: 16,fontFamily:'LangerReguler')),
                alignment: Alignment.center,
          ),
          );

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

If anyone is getting this error using Nginx, try adding the following to your server config:

server {
    listen 443 ssl;
    ...
}

The issue stems from Nginx serving an HTTP server to a client expecting HTTPS on whatever port you're listening on. When you specify ssl in the listen directive, you clear this up on the server side.

How to remove package using Angular CLI?

It's an open issue #900 on GitHub, unfortunately at this point of time it looks that in Angular CLI there's nothing like ng remove/rm/..., only using npm uninstall DEPENDENCY is the current workaround.

How to set the width of a RaisedButton in Flutter?

i would recommend using a MaterialButton, than you can do it like this:

new MaterialButton( 
 height: 40.0, 
 minWidth: 70.0, 
 color: Theme.of(context).primaryColor, 
 textColor: Colors.white, 
 child: new Text("push"), 
 onPressed: () => {}, 
 splashColor: Colors.redAccent,
)

How to clear Flutter's Build cache?

You can run flutter clean.

But that's most likely a problem with your IDE or similar, as flutter run creates a brand new apk. And hot reload push only modifications.

Try running your app using the command line flutter run and then press r or R for respectively hot-reload and full-reload.

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

Old one but I would add my answer as per my findings:

var ancestralState = context.findAncestorStateOfType<ParentState>();
      ancestralState.setState(() {
        // here you can access public vars and update state.
        ...
      });

Failed to start mongod.service: Unit mongod.service not found

Most probably unit mongodb.service is masked. Use following command to unmask it.

sudo systemctl unmask mongod

and re-run

sudo service mongod start

How to work with progress indicator in flutter?

{
isloading? progressIos:Container()

progressIos(int i) {
    return Container(
        color: i == 1
            ? AppColors.liteBlack
            : i == 2 ? AppColors.darkBlack : i == 3 ? AppColors.pinkBtn : '',
        child: Center(child: CupertinoActivityIndicator()));
  }
}

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

I came across this when upgrading from 5.8 to 6.x.

I had str_slug() in config/cache.php and config/session.php.

I have changed it to Str::slug() and the error has disappeared.

See https://laravel.com/docs/6.x/upgrade#helpers.

How to add a ListView to a Column in Flutter?

As have been mentioned by others above,Wrap listview with Expanded is the solution.

But when you deal with nested Columns you will also need to limit your ListView to a certain height (faced this problem a lot).

If anyone have another solution please, mention in comment or add answer.

Example

  SingleChildScrollView(
   child: Column(
     children: <Widget>[
       Image(image: ),//<< any widgets added
       SizedBox(),
       Column(
         children: <Widget>[
           Text('header'),  //<< any widgets added
            Expanded(child: 
            ListView.builder(
              //here your code
               scrollDirection: Axis.horizontal,
        itemCount: items.length,
        itemBuilder: (BuildContext context, int index) {
            return Container();
                   } 
         )
        ),
        Divider(),//<< any widgets added
         ],
       ),

     ],
   ), 
  );

How can I dismiss the on screen keyboard?

For me, the Listener above App widget is the best approach I've found:

Listener(
  onPointerUp: (_) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      currentFocus.focusedChild.unfocus();
    }
  },
  child: MaterialApp(
    title: 'Flutter Test App',
    theme: theme,
    ...
  ),
)

Flutter - Wrap text on overflow, like insert ellipsis or fade

If you simply place text as a child(ren) of a column, this is the easiest way to have text automatically wrap. Assuming you don't have anything more complicated going on. In those cases, I would think you would create your container sized as you see fit and put another column inside and then your text. This seems to work nicely. Containers want to shrink to the size of its contents, and this seems to naturally conflict with wrapping, which requires more effort.

Column(
  mainAxisSize: MainAxisSize.min,
  children: <Widget>[
    Text('This long text will wrap very nicely if there isn't room beyond the column\'s total width and if you have enough vertical space available to wrap into.',
      style: TextStyle(fontSize: 16, color: primaryColor),
      textAlign: TextAlign.center,),
  ],
),

How do I Set Background image in Flutter?

You can use the following code to set a background image to your app:

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/background.jpg"),
            fit: BoxFit.cover,
          ),
        ),
        // use any child here
        child: null
      ),
    );
  }

If your Container's child is a Column widget, you can use the crossAxisAlignment: CrossAxisAlignment.stretch to make your background image fill the screen.

Adding a splash screen to Flutter apps

Both @Collin Jackson and @Sniper are right. You can follow these steps to set up launch images in android and iOS respectively. Then in your MyApp(), in your initState(), you can use Future.delayed to set up a timer or call any api. Until the response is returned from the Future, your launch icons will be shown and then as the response come, you can move to the screen you want to go to after the splash screen. You can see this link : Flutter Splash Screen

How to send post request with x-www-form-urlencoded body

For HttpEntity, the below answer works

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

For reference: How to POST form data with Spring RestTemplate?

Selected tab's color in Bottom Navigation View

This will work:

setItemBackgroundResource(android.R.color.holo_red_light)

Make the size of a heatmap bigger with seaborn

I do not know how to solve this using code, but I do manually adjust the control panel at the right bottom in the plot figure, and adjust the figure size like:

f, ax = plt.subplots(figsize=(16, 12))

at the meantime until you get a matched size colobar. This worked for me.

How to unapply a migration in ASP.NET Core with EF Core

To completely remove all migrations and start all over again, do the following:

dotnet ef database update 0
dotnet ef migrations remove

curl: (35) SSL connect error

If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

This happened to me even on debug builds and just cleared all the module level and project level build folders and it worked, yeah just like that.

github: server certificate verification failed

I also was having this error when trying to clone a repository from Github on a Windows Subsystem from Linux console:

fatal: unable to access 'http://github.com/docker/getting-started.git/': server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

The solution from @VonC on this thread didn't work for me.

The solution from this Fabian Lee's article solved it for me:

openssl s_client -showcerts -servername github.com -connect github.com:443 </dev/null 2>/dev/null | sed -n -e '/BEGIN\ CERTIFICATE/,/END\ CERTIFICATE/ p'  > github-com.pem
cat github-com.pem | sudo tee -a /etc/ssl/certs/ca-certificates.crt

configuring project ':app' failed to find Build Tools revision

It happens because Build Tools revision 24.4.1 doesn't exist.

The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/ directory.

Don't confuse the Android SDK Tools with SDK Build Tools.

Change in your build.gradle

android {
   buildToolsVersion "23.0.2"
   // ...

}

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

Add

$mail->SMTPOptions = array(
'ssl' => array(
    'verify_peer' => false,
    'verify_peer_name' => false,
    'allow_self_signed' => true
));

before

mail->send()

and replace

require "mailer/class.phpmailer.php";

with

require "mailer/PHPMailerAutoload.php";

Lazy Loading vs Eager Loading

Consider the below situation

public class Person{
    public String Name{get; set;}
    public String Email {get; set;}
    public virtual Employer employer {get; set;}
}

public List<EF.Person> GetPerson(){
    using(EF.DbEntities db = new EF.DbEntities()){
       return db.Person.ToList();
    }
}

Now after this method is called, you cannot lazy load the Employer entity anymore. Why? because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force that to be loaded.

How to verify CuDNN installation?

Run ./mnistCUDNN in /usr/src/cudnn_samples_v7/mnistCUDNN

Here is an example:

cudnnGetVersion() : 7005 , CUDNN_VERSION from cudnn.h : 7005 (7.0.5)
Host compiler version : GCC 5.4.0
There are 1 CUDA capable devices on your machine :
device 0 : sms 30  Capabilities 6.1, SmClock 1645.0 Mhz, MemSize (Mb) 24446, MemClock 4513.0 Mhz, Ecc=0,    boardGroupID=0
Using device 0

No tests found for given includes Error, when running Parameterized Unit test in Android Studio

For me it worked when I've added @EnableJUnit4MigrationSupport class annotation.

(Of course together with already mentioned gradle libs and settings)

Error:java: javacTask: source release 8 requires target release 1.8

The quickest way I found:

  • press:CTRL + SHIFT + A (For Mac ? + SHIFT + A)
  • type: java compiler
  • press: ENTER

In the Settings window, set the Target bytecode to 1.8

(or 9 for java9)

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

I hit this error ("stat /bin/bash: no such file or directory") when running the command:

docker exec -it 80372bc2c41e /bin/bash

The solution was to identify the kind of terminal (or shell) that is available on the container. To do so, I ran:

docker inspect 80372bc2c41e

In the output from that command, I saw:

"Cmd": [
    "/bin/sh",
    "-c",
    "gunicorn -b 0.0.0.0:7082 server.app:app"
],

This tells me that there's a /bin/sh command available, and I was able to connect with:

docker exec -it 80372bc2c41e /bin/sh

How can I delete a user in linux when the system says its currently used in a process

First use pkill or kill -9 <pid> to kill the process.

Then use following userdel command to delete user,

userdel -f cafe_fixer

According to userdel man page:

-f, --force

This option forces the removal of the user account, even if the user is still logged in. It also forces userdel to remove the user's home directory and mail spool, even if another user uses the same home directory or if the mail spool is not owned by the specified user. If USERGROUPS_ENAB is defined to yes in /etc/login.defs and if a group exists with the same name as the deleted user, then this group will be removed, even if it is still the primary group of another user.

Edit 1: (by @Ajedi32)

Note: This option (i.e. --force) is dangerous and may leave your system in an inconsistent state.

Edit 2: (by @socketpair)

In spite of the description about some files, this key allows removing the user while it is in use. Don't forget to chdir / before, because this command will also remove home directory.

Export a list into a CSV or TXT file in R

Check out in here, worked well for me, with no limits in the output size, no omitted elements, even beyond 1000

Exporting large lists in R as .txt or .csv

Programmatically navigate to another view controller/scene

I already found the answer

Swift 4

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "nextView") as! NextViewController
self.present(nextViewController, animated:true, completion:nil)

Swift 3

let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

let nextViewController = storyBoard.instantiateViewControllerWithIdentifier("nextView") as NextViewController
self.presentViewController(nextViewController, animated:true, completion:nil)

Verify a certificate chain using openssl verify

You can easily verify a certificate chain with openssl. The fullchain will include the CA cert so you should see details about the CA and the certificate itself.

openssl x509 -in fullchain.pem -text -noout

curl: (60) SSL certificate problem: unable to get local issuer certificate

In my case it turned out to be a problem with the installation of my certificate on the service I was trying to consume with cURL. I failed to bundle/concatenate the intermediate and root certificates into my domain certificate. It wasn't obvious at first that this was the problem because Chrome worked it out and accepted the certificate in spite of leaving out the intermediate and root certificates.

After bundling the certificate, everything worked as expected. I bundled like this

$ cat intermediate.crt >> domain.crt

And repeated for all intermediate and the root certificate.

WAMP Cannot access on local network 403 Forbidden

If you are using WAMPServer 3 See bottom of answer

For WAMPServer versions <= 2.5

By default Wampserver comes configured as securely as it can, so Apache is set to only allow access from the machine running wamp. Afterall it is supposed to be a development server and not a live server.

Also there was a little error released with WAMPServer 2.4 where it used the old Apache 2.2 syntax instead of the new Apache 2.4 syntax for access rights.

You need to change the security setting on Apache to allow access from anywhere else, so edit your httpd.conf file.

Change this section from :

#   onlineoffline tag - don't remove
     Order Deny,Allow
     Deny from all
     Allow from 127.0.0.1
     Allow from ::1
     Allow from localhost

To :

#   onlineoffline tag - don't remove
    Require local
    Require ip 192.168.0

The Require local allows access from these ip's 127.0.0.1 & localhost & ::1.

The statement Require ip 192.168.0 will allow you to access the Apache server from any ip on your internal network. Also it will allow access using the server mechines actual ip address from the server machine, as you are trying to do.

WAMPServer 3 has a different method

In version 3 and > of WAMPServer there is a Virtual Hosts pre defined for localhost so you have to make the access privilage amendements in the Virtual Host definition config file

First dont amend the httpd.conf file at all, leave it as you found it.

Using the menus, edit the httpd-vhosts.conf file.

enter image description here

It should look like this :

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require local
    </Directory>
</VirtualHost>

Amend it to

<VirtualHost *:80>
    ServerName localhost
    DocumentRoot D:/wamp/www
    <Directory  "D:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

Hopefully you will have created a Virtual Host for your project and not be using the wamp\www folder for your site. In that case leave the localhost definition alone and make the change only to your Virtual Host.

Dont forget to restart Apache after making this change

Entity Framework rollback and remove bad migration

You have 2 options:

  • You can take the Down from the bad migration and put it in a new migration (you will also need to make the subsequent changes to the model). This is effectively rolling up to a better version.

    I use this option on things that have gone to multiple environments.

  • The other option is to actually run Update-Database –TargetMigration: TheLastGoodMigration against your deployed database and then delete the migration from your solution. This is kinda the hulk smash alternative and requires this to be performed against any database deployed with the bad version.

    Note: to rescaffold the migration you can use Add-Migration [existingname] -Force. This will however overwrite your existing migration, so be sure to do this only if you have removed the existing migration from the database. This does the same thing as deleting the existing migration file and running add-migration

    I use this option while developing.

Tried to Load Angular More Than Once

I had a similar issue, and for me the issue was due to some missing semicolons in the controller. The minification of the app was probably causing the code to execute incorrectly (most likely the resulting code was causing state mutations, which causes the view to render, and then the controller executes the code again, and so on recursively).

unknown error: Chrome failed to start: exited abnormally (Driver info: chromedriver=2.9

I was trying to run selenium on Jenkins with Mocha framework using wdio. So following are the steps to solve this issue:-

Install google chrome

sudo apt-get update 

sudo apt-get install google-chrome-stable

Install chrome-driver

wget http://chromedriver.storage.googleapis.com/2.23/chromedriver_linux64.zip
unzip chromedriver_linux64.zip

Run following commands to start selenium web server

nohup sudo Xvfb :10 -ac
export DISPLAY=:10
java -jar vendor/se/selenium-server-standalone/bin/selenium-server-standalone.jar -Dwebdriver.chrome.bin="/usr/bin/google-chrome" -Dwebdriver.chrome.driver="vendor/bin/chromedriver"

After this start you tests with wdio command

wdio wdio.conf.js

System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll?

It took me ages to work this one out, so for the benefit of searchers:

I had a bizarre issue whereby the application worked in debug, but gave the XamlParseException once released.

After fixing the x86/x64 issue as detailed by Katjoek, the issue remained.

The issue was that a CEF tutorial said to bring down System.Windows.Interactivity from NuGet (even thought it's in the Extensions section of references in .NET) and bringing down from NuGet sets specific version to true.

Once deployed, a different version of System.Windows.Interactivity was being packed by a different application.

It's refusal to use a different version of the dll caused the whole application to crash with XamlParseException.

Failed to install Python Cryptography package with PIP and setup.py

In case that you are dockerizing your python application, your Dockerfile needs to have something like:

FROM python:3.7-alpine

RUN apk add --update alpine-sdk && apk add libffi-dev openssl-dev

RUN pip install cryptography

server certificate verification failed. CAfile: /etc/ssl/certs/ca-certificates.crt CRLfile: none

Or simply run this comment to add the server Certificate to your database:

echo $(echo -n | openssl s_client -showcerts -connect yourserver.com:YourHttpGilabPort 2>/dev/null  | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p') >> /etc/ssl/certs/ca-certificates.crt

Then do git clone again.

How does an SSL certificate chain bundle work?

You need to use the openssl pkcs12 -export -chain -in server.crt -CAfile ...

See https://www.openssl.org/docs/apps/pkcs12.html

Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

ASP.NET Identity DbContext confusion

There is a lot of confusion about IdentityDbContext, a quick search in Stackoverflow and you'll find these questions:
" Why is Asp.Net Identity IdentityDbContext a Black-Box?
How can I change the table names when using Visual Studio 2013 AspNet Identity?
Merge MyDbContext with IdentityDbContext"

To answer to all of these questions we need to understand that IdentityDbContext is just a class inherited from DbContext.
Let's take a look at IdentityDbContext source:

/// <summary>
/// Base class for the Entity Framework database context used for identity.
/// </summary>
/// <typeparam name="TUser">The type of user objects.</typeparam>
/// <typeparam name="TRole">The type of role objects.</typeparam>
/// <typeparam name="TKey">The type of the primary key for users and roles.</typeparam>
/// <typeparam name="TUserClaim">The type of the user claim object.</typeparam>
/// <typeparam name="TUserRole">The type of the user role object.</typeparam>
/// <typeparam name="TUserLogin">The type of the user login object.</typeparam>
/// <typeparam name="TRoleClaim">The type of the role claim object.</typeparam>
/// <typeparam name="TUserToken">The type of the user token object.</typeparam>
public abstract class IdentityDbContext<TUser, TRole, TKey, TUserClaim, TUserRole, TUserLogin, TRoleClaim, TUserToken> : DbContext
    where TUser : IdentityUser<TKey, TUserClaim, TUserRole, TUserLogin>
    where TRole : IdentityRole<TKey, TUserRole, TRoleClaim>
    where TKey : IEquatable<TKey>
    where TUserClaim : IdentityUserClaim<TKey>
    where TUserRole : IdentityUserRole<TKey>
    where TUserLogin : IdentityUserLogin<TKey>
    where TRoleClaim : IdentityRoleClaim<TKey>
    where TUserToken : IdentityUserToken<TKey>
{
    /// <summary>
    /// Initializes a new instance of <see cref="IdentityDbContext"/>.
    /// </summary>
    /// <param name="options">The options to be used by a <see cref="DbContext"/>.</param>
    public IdentityDbContext(DbContextOptions options) : base(options)
    { }

    /// <summary>
    /// Initializes a new instance of the <see cref="IdentityDbContext" /> class.
    /// </summary>
    protected IdentityDbContext()
    { }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of Users.
    /// </summary>
    public DbSet<TUser> Users { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User claims.
    /// </summary>
    public DbSet<TUserClaim> UserClaims { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User logins.
    /// </summary>
    public DbSet<TUserLogin> UserLogins { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User roles.
    /// </summary>
    public DbSet<TUserRole> UserRoles { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of User tokens.
    /// </summary>
    public DbSet<TUserToken> UserTokens { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of roles.
    /// </summary>
    public DbSet<TRole> Roles { get; set; }

    /// <summary>
    /// Gets or sets the <see cref="DbSet{TEntity}"/> of role claims.
    /// </summary>
    public DbSet<TRoleClaim> RoleClaims { get; set; }

    /// <summary>
    /// Configures the schema needed for the identity framework.
    /// </summary>
    /// <param name="builder">
    /// The builder being used to construct the model for this context.
    /// </param>
    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<TUser>(b =>
        {
            b.HasKey(u => u.Id);
            b.HasIndex(u => u.NormalizedUserName).HasName("UserNameIndex").IsUnique();
            b.HasIndex(u => u.NormalizedEmail).HasName("EmailIndex");
            b.ToTable("AspNetUsers");
            b.Property(u => u.ConcurrencyStamp).IsConcurrencyToken();

            b.Property(u => u.UserName).HasMaxLength(256);
            b.Property(u => u.NormalizedUserName).HasMaxLength(256);
            b.Property(u => u.Email).HasMaxLength(256);
            b.Property(u => u.NormalizedEmail).HasMaxLength(256);
            b.HasMany(u => u.Claims).WithOne().HasForeignKey(uc => uc.UserId).IsRequired();
            b.HasMany(u => u.Logins).WithOne().HasForeignKey(ul => ul.UserId).IsRequired();
            b.HasMany(u => u.Roles).WithOne().HasForeignKey(ur => ur.UserId).IsRequired();
        });

        builder.Entity<TRole>(b =>
        {
            b.HasKey(r => r.Id);
            b.HasIndex(r => r.NormalizedName).HasName("RoleNameIndex");
            b.ToTable("AspNetRoles");
            b.Property(r => r.ConcurrencyStamp).IsConcurrencyToken();

            b.Property(u => u.Name).HasMaxLength(256);
            b.Property(u => u.NormalizedName).HasMaxLength(256);

            b.HasMany(r => r.Users).WithOne().HasForeignKey(ur => ur.RoleId).IsRequired();
            b.HasMany(r => r.Claims).WithOne().HasForeignKey(rc => rc.RoleId).IsRequired();
        });

        builder.Entity<TUserClaim>(b => 
        {
            b.HasKey(uc => uc.Id);
            b.ToTable("AspNetUserClaims");
        });

        builder.Entity<TRoleClaim>(b => 
        {
            b.HasKey(rc => rc.Id);
            b.ToTable("AspNetRoleClaims");
        });

        builder.Entity<TUserRole>(b => 
        {
            b.HasKey(r => new { r.UserId, r.RoleId });
            b.ToTable("AspNetUserRoles");
        });

        builder.Entity<TUserLogin>(b =>
        {
            b.HasKey(l => new { l.LoginProvider, l.ProviderKey });
            b.ToTable("AspNetUserLogins");
        });

        builder.Entity<TUserToken>(b => 
        {
            b.HasKey(l => new { l.UserId, l.LoginProvider, l.Name });
            b.ToTable("AspNetUserTokens");
        });
    }
}


Based on the source code if we want to merge IdentityDbContext with our DbContext we have two options:

First Option:
Create a DbContext which inherits from IdentityDbContext and have access to the classes.

   public class ApplicationDbContext 
    : IdentityDbContext
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    // Add additional items here as needed
}


Extra Notes:

1) We can also change asp.net Identity default table names with the following solution:

    public class ApplicationDbContext : IdentityDbContext
    {    
        public ApplicationDbContext(): base("DefaultConnection")
        {
        }

        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<IdentityUser>().ToTable("user");
            modelBuilder.Entity<ApplicationUser>().ToTable("user");

            modelBuilder.Entity<IdentityRole>().ToTable("role");
            modelBuilder.Entity<IdentityUserRole>().ToTable("userrole");
            modelBuilder.Entity<IdentityUserClaim>().ToTable("userclaim");
            modelBuilder.Entity<IdentityUserLogin>().ToTable("userlogin");
        }
    }

2) Furthermore we can extend each class and add any property to classes like 'IdentityUser', 'IdentityRole', ...

    public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    public ApplicationRole() 
    {
        this.Id = Guid.NewGuid().ToString();
    }

    public ApplicationRole(string name)
        : this()
    {
        this.Name = name;
    }

    // Add any custom Role properties/code here
}


// Must be expressed in terms of our custom types:
public class ApplicationDbContext 
    : IdentityDbContext<ApplicationUser, ApplicationRole, 
    string, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
{
    public ApplicationDbContext()
        : base("DefaultConnection")
    {
    }

    static ApplicationDbContext()
    {
        Database.SetInitializer<ApplicationDbContext>(new ApplicationDbInitializer());
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    // Add additional items here as needed
}

To save time we can use AspNet Identity 2.0 Extensible Project Template to extend all the classes.

Second Option:(Not recommended)
We actually don't have to inherit from IdentityDbContext if we write all the code ourselves.
So basically we can just inherit from DbContext and implement our customized version of "OnModelCreating(ModelBuilder builder)" from the IdentityDbContext source code

Entity framework self referencing loop detected

This happens because you're trying to serialize the EF object collection directly. Since department has an association to employee and employee to department, the JSON serializer will loop infinetly reading d.Employee.Departments.Employee.Departments etc...

To fix this right before the serialization create an anonymous type with the props you want

example (psuedo)code:

departments.select(dep => new { 
    dep.Id, 
    Employee = new { 
        dep.Employee.Id, dep.Employee.Name 
    }
});

Getting the button into the top right corner inside the div box

#button {
    line-height: 12px;
    width: 18px;
    font-size: 8pt;
    font-family: tahoma;
    margin-top: 1px;
    margin-right: 2px;
    position: absolute;
    top: 0;
    right: 0;
}

Android Studio: Gradle - build fails -- Execution failed for task ':dexDebug'

Make sure your AndroidManifest file contains a package name in the manifest node. Setting a package name fixed this problem for me.

Can't install via pip because of egg_info error

Try these: pip install --upgrade setuptools or easy_install -U setuptools

cURL not working (Error #77) for SSL connections on CentOS for non-root users

Turns out that the problem was with face that the script was running from a cPanel "email piped to script", so was running as the user, so is was a user problem, but was not affecting the web server at all.

The cause for the user not being able to access the /etc/pki directory was due to them only having jailed ssh access. Once I granted full access, it all worked fine.

Thanks for the info though, Remi.

Bootstrap combining rows (rowspan)

Divs stack vertically by default, so there is no need for special handling of "rows" within a column.

_x000D_
_x000D_
div {_x000D_
  height:50px;_x000D_
}_x000D_
.short-div {_x000D_
  height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
  <h1>Responsive Bootstrap</h1>_x000D_
  <div class="row">_x000D_
    <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
      <div class="short-div" style="background-color:green">Span 2</div>_x000D_
      <div class="short-div" style="background-color:purple">Span 2</div>_x000D_
    </div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
  <div class="row-fluid">_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
      <div class="short-div" style="background-color:#999">Span 6</div>_x000D_
      <div class="short-div">Span 6</div>_x000D_
    </div>_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's the fiddle.

Rails 4 Authenticity Token

This official doc - talks about how to turn off forgery protection for api properly http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html

Working Soap client example

String send = 
    "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
    "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n" +
    "        <soap:Body>\n" +
    "        </soap:Body>\n" +
    "</soap:Envelope>";

private static String getResponse(String send) throws Exception {
    String url = "https://api.comscore.com/KeyMeasures.asmx"; //endpoint
    String result = "";
    String username="user_name";
    String password="pass_word";
    String[] command = {"curl", "-u", username+":"+password ,"-X", "POST", "-H", "Content-Type: text/xml", "-d", send, url};
    ProcessBuilder process = new ProcessBuilder(command); 
    Process p;
    try {
        p = process.start();
        BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
        StringBuilder builder = new StringBuilder();
        String line = null;
        while ( (line = reader.readLine()) != null) {
                builder.append(line);
                builder.append(System.getProperty("line.separator"));
        }
        result = builder.toString();
    }
    catch (IOException e)
    {   System.out.print("error");
        e.printStackTrace();
    }

    return result;
}

How to have a drop down <select> field in a rails form?

Please have a look here

Either you can use rails tag Or use plain HTML tags

Rails tag

<%= select("Contact", "email_provider", Contact::PROVIDERS, {:include_blank => true}) %>

*above line of code would become HTML code(HTML Tag), find it below *

HTML tag

<select name="Contact[email_provider]">
  <option></option>
  <option>yahoo</option>
  <option>gmail</option>
  <option>msn</option>
</select>

How do I bottom-align grid elements in bootstrap fluid layout

Just set the parent to display:flex; and the child to margin-top:auto. This will place the child content at the bottom of the parent element, assuming the parent element has a height greater than the child element.

There is no need to try and calculate a value for margin-top when you have a height on your parent element or another element greater than your child element of interest within your parent element.

You have not concluded your merge (MERGE_HEAD exists)

Best approach is to undo the merge and perform the merge again. Often you get the order of things messed up. Try and fix the conflicts and get yourself into a mess.

So undo do it and merge again.

Make sure that you have the appropriate diff tools setup for your environment. I am on a mac and use DIFFMERGE. I think DIFFMERGE is available for all environments. Instructions are here: Install DIFF Merge on a MAC

I have this helpful resolving my conflicts: Git Basic-Merge-Conflicts

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

Solution: You must explicitly add the parameter -CAfile your-ca-file.pem.

Note: I tried also param -CApath mentioned in another answers, but is does not works for me.

Explanation: Error unable to get local issuer certificate means, that the openssl does not know your root CA cert.


Note: If you have web server with more domains, do not forget to add also -servername your.domain.net parameter. This parameter will "Set TLS extension servername in ClientHello". Without this parameter, the response will always contain the default SSL cert (not certificate, that match to your domain).

How to convert a UTF-8 string into Unicode?

What you have seems to be a string incorrectly decoded from another encoding, likely code page 1252, which is US Windows default. Here's how to reverse, assuming no other loss. One loss not immediately apparent is the non-breaking space (U+00A0) at the end of your string that is not displayed. Of course it would be better to read the data source correctly in the first place, but perhaps the data source was stored incorrectly to begin with.

using System;
using System.Text;

class Program
{
    static void Main(string[] args)
    {
        string junk = "déjÃ\xa0";  // Bad Unicode string

        // Turn string back to bytes using the original, incorrect encoding.
        byte[] bytes = Encoding.GetEncoding(1252).GetBytes(junk);

        // Use the correct encoding this time to convert back to a string.
        string good = Encoding.UTF8.GetString(bytes);
        Console.WriteLine(good);
    }
}

Result:

déjà

How to pass values arguments to modal.show() function in Bootstrap

I want to share how I did this. I spent the last few days rattling my head with how to pass a couple of parameters to the bootstrap modal dialog. After much head bashing, I came up with a rather simple way of doing this.

Here is my modal code:

<div class="modal fade" id="editGroupNameModal" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div id="editGroupName" class="modal-header">Enter new name for group </div>
        <div class="modal-body">
          <%= form_tag( { action: 'update_group', port: portnum } ) do %>
          <%= text_field_tag( :gid, "", { type: "hidden" })  %>
          <div class="input-group input-group-md">
          <span class="input-group-addon" style="font-size: 16px; padding: 3;" >Name</span>
          <%= text_field_tag( :gname, "", { placeholder: "New name goes here", class: "form-control", aria: {describedby: "basic-addon1"}})  %>
        </div>
        <div class="modal-footer">
          <%= submit_tag("Submit") %>
        </div>
        <% end %>
      </div>
    </div>
  </div>
</div>

And here is the simple javascript to change the gid, and gname input values:

function editGroupName(id, name) {
    $('input#gid').val(id);
    $('input#gname.form-control').val(name);
  }

I just used the onclick event in a link:

//                                                                              &#39; is single quote
//                                                                                   ('1', 'admin')
<a data-toggle="modal" data-target="#editGroupNameModal" onclick="editGroupName(&#39;1&#39;, &#39;admin&#39;); return false;" href="#">edit</a>

The onclick fires first, changing the value property of the input boxes, so when the dialog pops up, values are in place for the form to submit.

I hope this helps someone someday. Cheers.

Fluid or fixed grid system, in responsive design, based on Twitter Bootstrap

Interesting discussion. I was asking myself this question too. The main difference between fluid and fixed is simply that the fixed layout has a fixed width in terms of the whole layout of the website (viewport). If you have a 960px width viewport each colum has a fixed width which will never change.

The fluid layout behaves different. Imagine you have set the width of your main layout to 100% width. Now each column will only be calculated to it's relative size (i.e. 25%) and streches as the browser will be resized. So based on your layout purpose you can select how your layout behaves.

Here is a good article about fluid vs. flex.

C# ASP.NET MVC Return to Previous Page

I am assuming (please correct me if I am wrong) that you want to re-display the edit page if the edit fails and to do this you are using a redirect.

You may have more luck by just returning the view again rather than trying to redirect the user, this way you will be able to use the ModelState to output any errors too.

Edit:

Updated based on feedback. You can place the previous URL in the viewModel, add it to a hidden field then use it again in the action that saves the edits.

For instance:

public ActionResult Index()
{
    return View();
}

[HttpGet] // This isn't required
public ActionResult Edit(int id)
{
   // load object and return in view
   ViewModel viewModel = Load(id);

   // get the previous url and store it with view model
   viewModel.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;

   return View(viewModel);
}

[HttpPost]
public ActionResult Edit(ViewModel viewModel)
{
   // Attempt to save the posted object if it works, return index if not return the Edit view again

   bool success = Save(viewModel);
   if (success)
   {
       return Redirect(viewModel.PreviousUrl);
   }
   else
   {
      ModelState.AddModelError("There was an error");
      return View(viewModel);
   }
}

The BeginForm method for your view doesn't need to use this return URL either, you should be able to get away with:

@model ViewModel

@using (Html.BeginForm())
{
    ...
    <input type="hidden" name="PreviousUrl" value="@Model.PreviousUrl" />
}

Going back to your form action posting to an incorrect URL, this is because you are passing a URL as the 'id' parameter, so the routing automatically formats your URL with the return path.

This won't work because your form will be posting to an controller action that won't know how to save the edits. You need to post to your save action first, then handle the redirect within it.

Celery Received unregistered task of type (run example)

I think you need to restart the worker server. I meet the same problem and solve it by restarting.

Rails: How does the respond_to block work?

"Format" is your response type. Could be json or html, for example. It's the format of the output your visitor will receive.

Git conflict markers

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

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

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

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

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

Pushing to Git returning Error Code 403 fatal: HTTP request failed

One another possible reason is, you might have exceeded their plan limit.

To fix this issue and restore write access to the repo, either your account plan will need to be upgraded, or some of your collaborators will need to be removed.

Adding a column to an existing table in a Rails migration

You can also add column to a specific position using before column or after column like:

rails generate migration add_dob_to_customer dob:date

The migration file will generate the following code except after: :email. you need to add after: :email or before: :email

class AddDobToCustomer < ActiveRecord::Migration[5.2]
  def change
    add_column :customers, :dob, :date, after: :email
  end
end

Differences between Html.TextboxFor and Html.EditorFor in MVC and Razor

The Html.TextboxFor always creates a textbox (<input type="text" ...).

While the EditorFor looks at the type and meta information, and can render another control or a template you supply.

For example for DateTime properties you can create a template that uses the jQuery DatePicker.

Rails: How to run `rails generate scaffold` when the model already exists?

This command should do the trick:

$ rails g scaffold movie --skip

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Load an image from a url into a PictureBox

The PictureBox.Load(string url) method "sets the ImageLocation to the specified URL and displays the image indicated."

Github: error cloning my private repository

I faced this while git pull. For mine edited the global git config file that fixed problem.

Goto your home folder and open .gitconfig file. Usually C:\Users\.gitconfig

If the file is not there create it

[http]
sslcainfo = E:\systools\git-1.8.5.2\bin\curl-ca-bundle.crt

There you have to given your own git installation path. I have used portable version of git here.

Then git clone / pull it will work.

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

I simply disabled the SSL certificate authentication and used the simple user name password login as shown belowenter image description here

How do I deal with certificates using cURL while trying to access an HTTPS url?

Just find this solution works perfectly for me.

echo 'cacert=/etc/ssl/certs/ca-certificates.crt' > ~/.curlrc

I found this solution from here

Memory address of variables in Java

This is not memory address This is classname@hashcode
Which is the default implementation of Object.toString()

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

where

Class name = full qualified name or absolute name (ie package name followed by class name) hashcode = hexadecimal format (System.identityHashCode(obj) or obj.hashCode() will give you hashcode in decimal format).

Hint:
The confusion root cause is that the default implementation of Object.hashCode() use the internal address of the object into an integer

This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.

And of course, some classes can override both default implementations either for toString() or hashCode()

If you need the default implementation value of hashcode() for a object which overriding it,
You can use the following method System.identityHashCode(Object x)

Undo scaffolding in Rails

To generate scaffolding :

rails generate scaffold xyz

To revert scaffolding :

rails destroy scaffold xyz

Setting the default value of a DateTime Property to DateTime.Now inside the System.ComponentModel Default Value Attrbute

I also wanted this and came up with this solution (I'm only using the date part - a default time makes no sense as a PropertyGrid default):

public class DefaultDateAttribute : DefaultValueAttribute {
  public DefaultDateAttribute(short yearoffset)
    : base(DateTime.Now.AddYears(yearoffset).Date) {
  }
}

This just creates a new attribute that you can add to your DateTime property. E.g. if it defaults to DateTime.Now.Date:

[DefaultDate(0)]

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

I used the sdk.

eg:

using SevenZip.Compression.LZMA;
private static void CompressFileLZMA(string inFile, string outFile)
{
   SevenZip.Compression.LZMA.Encoder coder = new SevenZip.Compression.LZMA.Encoder();

   using (FileStream input = new FileStream(inFile, FileMode.Open))
   {
      using (FileStream output = new FileStream(outFile, FileMode.Create))
      {
          coder.Code(input, output, -1, -1, null);
          output.Flush();
      }
   }
}

How do I correct the character encoding of a file?

EDIT: A simple possibility to eliminate before getting into more complicated solutions: have you tried setting the character set to utf8 in the text editor in which you're reading the file? This could just be a case of somebody sending you a utf8 file that you're reading in an editor set to say cp1252.

Just taking the two examples, this is a case of utf8 being read through the lens of a single-byte encoding, likely one of iso-8859-1, iso-8859-15, or cp1252. If you can post examples of other problem characters, it should be possible to narrow that down more.

As visual inspection of the characters can be misleading, you'll also need to look at the underlying bytes: the § you see on screen might be either 0xa7 or 0xc2a7, and that will determine the kind of character set conversion you have to do.

Can you assume that all of your data has been distorted in exactly the same way - that it's come from the same source and gone through the same sequence of transformations, so that for example there isn't a single é in your text, it's always ç? If so, the problem can be solved with a sequence of character set conversions. If you can be more specific about the environment you're in and the database you're using, somebody here can probably tell you how to perform the appropriate conversion.

Otherwise, if the problem characters are only occurring in some places in your data, you'll have to take it instance by instance, based on assumptions along the lines of "no author intended to put ç in their text, so whenever you see it, replace by ç". The latter option is more risky, firstly because those assumptions about the intentions of the authors might be wrong, secondly because you'll have to spot every problem character yourself, which might be impossible if there's too much text to visually inspect or if it's written in a language or writing system that's foreign to you.

Referencing a string in a string array resource with xml

Maybe this would help:

String[] some_array = getResources().getStringArray(R.array.your_string_array)

So you get the array-list as a String[] and then choose any i, some_array[i].

@Resource vs @Autowired

I would like to emphasize one comment from @Jules on this answer to this question. The comment brings a useful link: Spring Injection with @Resource, @Autowired and @Inject. I encourage you to read it entirely, however here is a quick summary of its usefulness:

How annotations select the right implementation?

@Autowired and @Inject

  1. Matches by Type
  2. Restricts by Qualifiers
  3. Matches by Name

@Resource

  1. Matches by Name
  2. Matches by Type
  3. Restricts by Qualifiers (ignored if match is found by name)

Which annotations (or combination of) should I use for injecting my beans?

  1. Explicitly name your component [@Component("beanName")]

  2. Use @Resource with the name attribute [@Resource(name="beanName")]

Why should I not use @Qualifier?

Avoid @Qualifier annotations unless you want to create a list of similar beans. For example you may want to mark a set of rules with a specific @Qualifier annotation. This approach makes it simple to inject a group of rule classes into a list that can be used for processing data.

Does bean injection slow my program?

Scan specific packages for components [context:component-scan base-package="com.sourceallies.person"]. While this will result in more component-scan configurations it reduces the chance that you’ll add unnecessary components to your Spring context.


Reference: Spring Injection with @Resource, @Autowired and @Inject

Filtering DataGridView without changing datasource

//"Comment" Filter datagrid without changing dataset,Perfectly works.

            (dg.ItemsSource as ListCollectionView).Filter = (d) =>
            {
                DataRow myRow = ((System.Data.DataRowView)(d)).Row;
                if (myRow["FName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()) || myRow["LName"].ToString().ToUpper().Contains(searchText.ToString().ToUpper()))
                    return true; //if want to show in grid
                return false;    //if don't want to show in grid
            };         

Capturing count from an SQL query

You'll get converting errors with:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Use instead:

string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
    found = true; 
} else {
    found = false; 
}

Java: JSON -> Protobuf & back conversion

Well, there is no shortcut to do it as per my findings, but somehow you
an achieve it in few simple steps

First you have to declare a bean of type 'ProtobufJsonFormatHttpMessageConverter'

@Bean  
@Primary  
public ProtobufJsonFormatHttpMessageConverter protobufHttpMessageConverter() {  
  return new ProtobufJsonFormatHttpMessageConverter(JsonFormat.parser(), JsonFormat.printer());  
}  

Then you can just write an Utility class like ResponseBuilder, because it can parse the request by default but without these changes it can not produce Json response. and then you can write few methods to convert the response types to its related object type.

public static <T> T build(Message message, Class<T> type) {
  Printer printer = JsonFormat.printer();
  Gson gson = new Gson();
  try {
    return gson.fromJson(printer.print(message), type);
  } catch (JsonSyntaxException | InvalidProtocolBufferException e) {
    throw new ApiException(HttpStatus.INTERNAL_SERVER_ERROR, "Response   conversion Error", e);
  }
}

Then you can call this method from your controller class as last line like -

return ResponseBuilder.build(<returned_service_object>, <Type>);

Hope this will help you to implement protobuf in json format.

no module named urllib.parse (How should I install it?)

python3 supports urllib.parse and python2 supports urlparse

If you want both compatible then the following code can help.

import sys

if ((3, 0) <= sys.version_info <= (3, 9)):
    from urllib.parse import urlparse
elif ((2, 0) <= sys.version_info <= (2, 9)):
    from urlparse import urlparse

Update: Change if condition to support higher versions if (3, 0) <= sys.version_info:.

How to export and import a .sql file from command line with options?

since I have no enough reputation to comment after the highest post, so I add here.

use '|' on linux platform to save disk space.

thx @Hariboo, add events/triggers/routints parameters

mysqldump -x -u [uname] -p[pass]  -C --databases db_name  --events --triggers --routines | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/ '  | awk '{ if (index($0,"GTID_PURGED")) { getline; while (length($0) > 0) { getline; } } else { print $0 } }'  | grep -iv 'set @@' | trickle -u 10240 mysql -u username -p -h localhost DATA-BASE-NAME

some issues/tips:

Error: ......not exist when using LOCK TABLES

# --lock-all-tables,-x , this parameter is to keep data consistency because some transaction may still be working like schedule.
# also you need check and confirm: grant all privileges on *.* to root@"%" identified by "Passwd";

ERROR 2006 (HY000) at line 866: MySQL server has gone away mysqldump: Got errno 32 on write

# set this values big enough on destination mysql server, like: max_allowed_packet=1024*1024*20
# use compress parameter '-C'
# use trickle to limit network bandwidth while write data to destination server

ERROR 1419 (HY000) at line 32730: You do not have the SUPER privilege and binary logging is enabled (you might want to use the less safe log_bin_trust_function_creators variable)

# set SET GLOBAL log_bin_trust_function_creators = 1;
# or use super user import data

ERROR 1227 (42000) at line 138: Access denied; you need (at least one of) the SUPER privilege(s) for this operation mysqldump: Got errno 32 on write

# add sed/awk to avoid some privilege issues

hope this help!

Simultaneously merge multiple data.frames in a list

Another question asked specifically how to perform multiple left joins using dplyr in R . The question was marked as a duplicate of this one so I answer here, using the 3 sample data frames below:

x <- data.frame(i = c("a","b","c"), j = 1:3, stringsAsFactors=FALSE)
y <- data.frame(i = c("b","c","d"), k = 4:6, stringsAsFactors=FALSE)
z <- data.frame(i = c("c","d","a"), l = 7:9, stringsAsFactors=FALSE)

Update June 2018: I divided the answer in three sections representing three different ways to perform the merge. You probably want to use the purrr way if you are already using the tidyverse packages. For comparison purposes below, you'll find a base R version using the same sample dataset.


1) Join them with reduce from the purrr package:

The purrr package provides a reduce function which has a concise syntax:

library(tidyverse)
list(x, y, z) %>% reduce(left_join, by = "i")
#  A tibble: 3 x 4
#  i       j     k     l
#  <chr> <int> <int> <int>
# 1 a      1    NA     9
# 2 b      2     4    NA
# 3 c      3     5     7

You can also perform other joins, such as a full_join or inner_join:

list(x, y, z) %>% reduce(full_join, by = "i")
# A tibble: 4 x 4
# i       j     k     l
# <chr> <int> <int> <int>
# 1 a     1     NA     9
# 2 b     2     4      NA
# 3 c     3     5      7
# 4 d     NA    6      8

list(x, y, z) %>% reduce(inner_join, by = "i")
# A tibble: 1 x 4
# i       j     k     l
# <chr> <int> <int> <int>
# 1 c     3     5     7

2) dplyr::left_join() with base R Reduce():

list(x,y,z) %>%
    Reduce(function(dtf1,dtf2) left_join(dtf1,dtf2,by="i"), .)

#   i j  k  l
# 1 a 1 NA  9
# 2 b 2  4 NA
# 3 c 3  5  7

3) Base R merge() with base R Reduce():

And for comparison purposes, here is a base R version of the left join based on Charles's answer.

 Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "i", all.x = TRUE),
        list(x,y,z))
#   i j  k  l
# 1 a 1 NA  9
# 2 b 2  4 NA
# 3 c 3  5  7

Error: Segmentation fault (core dumped)

It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga

faulthandler.enable()
// bad code goes here

or

$ python3 -q -X faulthandler
>>> /// bad cod goes here

How to get tf.exe (TFS command line client)?

You need to install Team Explorer, it's best to install the version of Team Explorer that matches the version of TFS you are using e.g. if you're using TFS 2010 then install Team Explorer 2010.

2012 version http://www.microsoft.com/en-gb/download/details.aspx?id=30656

2013 version http://www.microsoft.com/en-us/download/details.aspx?id=40776

2019 version https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=TeamExplorer&rel=16

You also might be interested in the TFS power tools. They add some extra command line features (using tfpt.exe) and also add some extra IDE features.

Append TimeStamp to a File Name

You can use below instead:

DateTime.Now.Ticks

PostgreSQL 'NOT IN' and subquery

You could also use a LEFT JOIN and IS NULL condition:

SELECT 
  mac, 
  creation_date 
FROM 
  logs
    LEFT JOIN consols ON logs.mac = consols.mac
WHERE 
  logs_type_id=11
AND
  consols.mac IS NULL;

An index on the "mac" columns might improve performance.

How to use clock() in C++

you can measure how long your program works. The following functions help measure the CPU time since the start of the program:

  • C++ (double)clock() / CLOCKS PER SEC with ctime included.
  • python time.clock() returns floating-point value in seconds.
  • Java System.nanoTime() returns long value in nanoseconds.

my reference: Algorithms toolbox week 1 course part of data structures and algorithms specialization by University of California San Diego & National Research University Higher School of Economics

so you can add this line of code after your algorithm

cout << (double)clock() / CLOCKS_PER_SEC ;

Expected Output: the output representing the number of clock ticks per second

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

I created a working demo of a landscape/portrait layout but the zoom must be disabled for it to work without JavaScript:

http://matthewjamestaylor.com/blog/ipad-layout-with-landscape-portrait-modes

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

The query you are after will be

SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'

Java - removing first character of a string

In Java, remove leading character only if it is a certain character

Use the Java ternary operator to quickly check if your character is there before removing it. This strips the leading character only if it exists, if passed a blank string, return blankstring.

String header = "";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "foobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

header = "#moobar";
header = header.startsWith("#") ? header.substring(1) : header;
System.out.println(header);

Prints:

blankstring
foobar
moobar

Java, remove all the instances of a character anywhere in a string:

String a = "Cool";
a = a.replace("o","");
//variable 'a' contains the string "Cl"

Java, remove the first instance of a character anywhere in a string:

String b = "Cool";
b = b.replaceFirst("o","");
//variable 'b' contains the string "Col"

SQL Case Expression Syntax?

Case statement syntax in SQL SERVER:

CASE column
   WHEN value1 THEN 1
   WHEN value3 THEN 2
   WHEN value3 THEN 3
   WHEN value1 THEN 4
   ELSE ''
END

And we can use like below also:

CASE 
   WHEN column=value1 THEN 1
   WHEN column=value3 THEN 2
   WHEN column=value3 THEN 3
   WHEN column=value1 THEN 4
   ELSE ''
END

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

Jupyter has its own PATH variable, JUPYTER_PATH.

Adding this line to the .bashrc file worked for me:

export JUPYTER_PATH=<directory_for_your_module>:$JUPYTER_PATH

How does Git handle symbolic links?

"Editor's" note: This post may contain outdated information. Please see comments and this question regarding changes in Git since 1.6.1.

Symlinked directories:

It's important to note what happens when there is a directory which is a soft link. Any Git pull with an update removes the link and makes it a normal directory. This is what I learnt hard way. Some insights here and here.

Example

Before

 ls -l
 lrwxrwxrwx 1 admin adm   29 Sep 30 15:28 src/somedir -> /mnt/somedir

git add/commit/push

It remains the same

After git pull AND some updates found

 drwxrwsr-x 2 admin adm 4096 Oct  2 05:54 src/somedir

C split a char array into different variables

In addition, you can use sscanf for some very simple scenarios, for example when you know exactly how many parts the string has and what it consists of. You can also parse the arguments on the fly. Do not use it for user inputs because the function will not report conversion errors.

Example:

char text[] = "1:22:300:4444:-5";
int i1, i2, i3, i4, i5;
sscanf(text, "%d:%d:%d:%d:%d", &i1, &i2, &i3, &i4, &i5);
printf("%d, %d, %d, %d, %d", i1, i2, i3, i4, i5);

Output:

1, 22, 300, 4444, -5

For anything more advanced, strtok() and strtok_r() are your best options, as mentioned in other answers.

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

PerformSelector:WithObject always takes an object, so in order to pass arguments like int/double/float etc..... You can use something like this.

//NSNumber is an object..

    [self performSelector:@selector(setUserAlphaNumber:) withObject: [NSNumber numberWithFloat: 1.0f]
    afterDelay:1.5];

    -(void) setUserAlphaNumber: (NSNumber*) number{

     [txtUsername setAlpha: [number floatValue] ];
    }

Same way you can use [NSNumber numberWithInt:] etc.... and in the receiving method you can convert the number into your format as [number int] or [number double].

Strings as Primary Keys in SQL Database

By default ASPNetUserIds are 128 char strings and performance is just fine.

If the key HAS to be unique in the table it should be the Key. Here's why;

primary string key = Correct DB relationships, 1 string key(The primary), and 1 string Index(The Primary).

The other option is a typical int Key, but if the string HAS to be unique you'll still probably need to add an index because of non-stop queries to validate or check that its unique.

So using an int identity key = Incorrect DB Relationships, 1 int key(Primary), 1 int index(Primary), Probably a unique string Index, and manually having to validate the same string doesn't exist(something like a sql check maybe).

To get better performance using an int over a string for the primary key, when the string HAS to be unique, it would have to be a very odd situation. I've always preferred to use string keys. And as a good rule of thumb, don't denormalize a database until you NEED to.

How to iterate through two lists in parallel?

Python 3:

import itertools as it

for foo, bar in list(it.izip_longest(list1, list2)):
    print(foo, bar)

How to detect a loop in a linked list?

This code is optimized and will produce result faster than with the one chosen as the best answer.This code saves from going into a very long process of chasing the forward and backward node pointer which will occur in the following case if we follow the 'best answer' method.Look through the dry run of the following and you will realize what I am trying to say.Then look at the problem through the given method below and measure the no. of steps taken to find the answer.

1->2->9->3 ^--------^

Here is the code:

boolean loop(node *head)
{
 node *back=head;
 node *front=head;

 while(front && front->next)
 {
  front=front->next->next;
  if(back==front)
  return true;
  else
  back=back->next;
 }
return false
}

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

STEP 1: Include the following in OnConfiguring()

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
            .AddJsonFile("appsettings.json")
            .Build();
        optionsBuilder.UseSqlServer(configuration.GetConnectionString("DefaultConnection"));
    }

STEP 2: Create appsettings.json:

  {
    "ConnectionStrings": {       
      "DefaultConnection": "Server=YOURSERVERNAME; Database=YOURDATABASENAME; Trusted_Connection=True; MultipleActiveResultSets=true"        
    } 
  }

STEP 3: Hard copy appsettings.json to the correct directory

  Hard copy appsettings.json.config to the directory specified in the AppDomain.CurrentDomain.BaseDirectory directory. 
  Use your debugger to find out which directory that is.        

Assumption: you have already included package Microsoft.Extensions.Configuration.Json (get it from Nuget) in your project.

python's re: return True if string contains regex pattern

import re
word = 'fubar'
regexp = re.compile(r'ba[rzd]')
if regexp.search(word):
  print 'matched'

Horizontal swipe slider with jQuery and touch devices support?

Take a look at iScroll v4 here: http://cubiq.org/iscroll-4

It may not be jQuery, but it works on Desktop Mobile, and iPad quite well; I've used it on many projects and combined it with jQuery.

Good Luck!

how to get current month and year

using System.Globalization;

LblMonth.Text = DateTime.Now.Month.ToString();

DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
int month = Convert.ToInt16(LblMonth.Text);

LblMonth.Text = dinfo.GetMonthName(month);

how to convert rgb color to int in java

You want to use intvalue = Color.parseColor("#" + colorobject);

VBScript -- Using error handling

VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.

On Error Resume Next

DoStep1

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStep1: " & Err.Description
  Err.Clear
End If

DoStep2

If Err.Number <> 0 Then
  WScript.Echo "Error in DoStop2:" & Err.Description
  Err.Clear
End If

'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0

The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.

Java Minimum and Maximum values in Array

Imho one of the simplest Solutions is: -

//MIN NUMBER
Collections.sort(listOfNumbers);
listOfNumbers.get(0);

//MAX NUMBER
Collections.sort(listOfNumbers);
Collections.reverse(listOfNumbers);
listOfNumbers.get(0);

Commit empty folder structure (with git)

Just add a file .gitkeep in every folder you want committed.

On windows do so by right clicking when in the folder and select: Git bash from here. Then type: touch .gitkeep

What's the best visual merge tool for Git?

You can install ECMerge diff/merge tool on your Linux, Mac or Windows. It is pre-configured in Git, so just using git mergetool will do the job.

sort dict by value python

no lambda method

# sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
    for k, v in d.items():
        if v == i:
            return (k)

sortvaluelist = sorted(d.values())
sortresult ={}
for i1 in sortvaluelist:   
    key = getkeybyvalue(d,i1)
    sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')

Where can I find Android's default icons?

You can find the default Android menu icons here - link is broken now.

Update: You can find Material Design icons here.

Read/write to file using jQuery

You will need to handle your file access through web programming language, such as PHP or ASP.net.

To set this up, you would:

  • Create a script that handles the file reading and writing. This should be visible to the browser.

  • Send jQuery ajax requests to that script that either write data or read data. You would need to pass all of your read/write information through the request parameters. You can learn more about this in the jQuery ajax documentation.

Make sure that you sanitize any data that you are storing, since this could potentially be a security risk. However, this is really just standard flat-file data storage, and is not necessarily that unusual.

As Paolo pointed out, there is no way to directly read/write to a file through jQuery or any other type of javascript.

How to deploy a Java Web Application (.war) on tomcat?

  • copy the .war file in the webapps folder
  • upload the file using the manager application - http://host:port/manager. You will have to setup some users beforehand.
  • (not recommended, but working) - manually extract the .war file as a .zip archive and place the extracted files in webapps/webappname

Sometimes administrators configure tomcat so that war files are deployed outside the tomcat folder. Even in that case:

After you have it deployed (check the /logs dir for any problems), it should be accessible via: http://host:port/yourwebappname/. So in your case, one of those:

http://bilgin.ath.cx/TestWebApp/
http://bilgin.ath.cx:8080/TestWebApp/

If you don't manage by doing the above and googling - turn to your support. There might be an alternative port, or there might be something wrong with the application (and therefore in the logs)

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

The backend version is not supported to design database diagrams or tables

I was having the same problem, although I solved out by creating the table using a script query instead of doing it graphically. See the snipped below:

USE [Database_Name]
GO

CREATE TABLE [dbo].[Table_Name](
[tableID] [int] IDENTITY(1,1) NOT NULL,
[column_2] [datatype] NOT NULL,
[column_3] [datatype] NOT NULL,

CONSTRAINT [PK_Table_Name] PRIMARY KEY CLUSTERED 
(
[tableID] ASC
)
)

java.net.ConnectException: failed to connect to /192.168.253.3 (port 2468): connect failed: ECONNREFUSED (Connection refused)

you can covert domain to IP address because every Domain have specific IP address, then you will solve that issue. I hope this will help you.

Text File Parsing with Python

From the accepted answer, it looks like your desired behaviour is to turn

skip 0
skip 1
skip 2
skip 3
"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636

into

2012,06,23,03,09,13.23,4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,NAN,-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636

If that's right, then I think something like

import csv

with open("test.dat", "rb") as infile, open("test.csv", "wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, quoting=False)
    for i, line in enumerate(reader):
        if i < 4: continue
        date = line[0].split()
        day = date[0].split('-')
        time = date[1].split(':')
        newline = day + time + line[1:]
        writer.writerow(newline)

would be a little simpler than the reps stuff.

How can I set the color of a selected row in DataGrid

Got it. Add the following within the DataGrid.Resources section:

  <DataGrid.Resources>
     <Style TargetType="{x:Type dg:DataGridCell}">
        <Style.Triggers>
            <Trigger Property="dg:DataGridCell.IsSelected" Value="True">
                <Setter Property="Background" Value="#CCDAFF" />
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>

How to jump to a particular line in a huge text file?

Can use this function to return line n:

def skipton(infile, n):
    with open(infile,'r') as fi:
        for i in range(n-1):
            fi.next()
        return fi.next()

Visual Studio 2015 or 2017 does not discover unit tests

EDIT 2016-10-19 (PowerShell script)

This issue still returns every now and then. I wrote a small PowerShell snippet to automate clearing the relevant cache/temp folder/files for me. I'm sharing it here for future readers:

@(
"$env:TEMP"
"$env:LOCALAPPDATA\Microsoft\UnitTest"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\1033\SpecificFolderCache.xml"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\1033\ProjectTemplateMRU.xml"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\ComponentModelCache"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\Designer\ShadowCache"
"$env:LOCALAPPDATA\Microsoft\VisualStudio\14.0\ImageLibrary\cache"
"$env:LOCALAPPDATA\Microsoft\VisualStudio Services\6.0\Cache"
"$env:LOCALAPPDATA\Microsoft\WebsiteCache"
"$env:LOCALAPPDATA\NuGet\Cache"
) |% { Remove-Item -Path $_ -Recurse -Force }

Make sure to close Visual Studio beforehand and it's probably a good idea to reboot afterwards.

Deleting the TEMP folder may not be necessary and may in some cases even be undesirable, so I would recommend trying without clearing the TEMP folder first. Just omit the "$env:TEMP".

Original answer 2015-04-12

The problem was "solved" after a thorough cleaning of Visual Studio-related temp/cache folders.

Since I did not have the time to go through everything one-by-one and then test in-between, I unfortunately don't know which one actually caused the problem.

These are the exact steps I've taken:

  1. Closed Visual Studio
  2. Used CCleaner to clear system and browser temp files/folders
  3. Manually cleared/deleted the following files/folders:

    • %USERPROFILE%\AppData\Local\assembly
    • %USERPROFILE%\AppData\Local\Microsoft\UnitTest
    • %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\1033\SpecificFolderCache.xml
    • %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\1033\ProjectTemplateMRU.xml
    • %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\ComponentModelCache
    • %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\Designer\ShadowCache
    • %USERPROFILE%\AppData\Local\Microsoft\VisualStudio\14.0\ImageLibrary\cache
    • %USERPROFILE%\AppData\Local\Microsoft\VisualStudio Services\6.0\Cache
    • %USERPROFILE%\AppData\Local\Microsoft\WebsiteCache
    • %USERPROFILE%\AppData\Local\NuGet\Cache
    • %USERPROFILE%\AppData\Local\Temp

Update rows in one table with data from another table based on one column in each being equal

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      );

Or this (if t2.column1 <=> t1.column1 are many to one and anyone of them is good):

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
    and
      rownum = 1    
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      ); 

jQuery Validation plugin: validate check box

There is the easy way

HTML:

<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]"  />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>

JQUERY:

$("#submit").on("click",function(){
    if (($("input[name*='test']:checked").length)<=0) {
        alert("You must check at least 1 box");
    }
    return true;
});

For this you not need any plugin. Enjoy;)

How to hide Soft Keyboard when activity starts

Use the following code to Hide the softkeyboard first time when you start the Activity

getActivity().getWindow().setSoftInputMode(WindowManager.
LayoutParams.SOFT_INPUT_STATE_HIDDEN);

How to convert a Date to a formatted string in VB.net?

I like:

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
myDate.ToString(timeFormat)

Easy to maintain if you need to use it in several parts of your code, date formats always seem to change sooner or later.

How to loop through a dataset in powershell?

The parser is having trouble concatenating your string. Try this:

write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])

Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:

write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"

Python script to convert from UTF-8 to ASCII

data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")

Load local images in React.js

In React or any Javascript modules that internally use Webpack, if the src attribute value of img is given as a path in string format as given below

e.g. <img src={'/src/images/logo.png'} /> or <img src='/src/images/logo.png' />

then during build, the final HTML page built contains src='/src/images/logo.png'. This path is not read during build time, but is read during rendering in browser. At the rendering time, if the logo.png is not found in the /src/images directory, then the image would not render. If you open the console in browser, you can see the 404 error for the image. I believe you meant to use ./src directory instead of /src directory. In that case, the development directory ./src is not available to the browser. When the page is loaded in browser only the files in the 'public' directory are available to the browser. So, the relative path ./src is assumed to be public/src directory and if the logo.png is not found in public/src/images/ directory, it would not render the image.

So, the solution for this problem is either to put your image in the public directory and reference the relative path from public directory or use import or require keywords in React or any Javascript module to inform the Webpack to read this path during build phase and include the image in the final build output. The details of both these methods has been elaborated by Dan Abramov in his answer, please refer to it or use the link: https://create-react-app.dev/docs/adding-images-fonts-and-files/

Button button = findViewById(R.id.button) always resolves to null in Android Studio

R.id.button is not part of R.layout.activity_main. How should the activity find it in the content view?

The layout that contains the button is displayed by the Fragment, so you have to get the Button there, in the Fragment.

What does question mark and dot operator ?. mean in C# 6.0?

It's the null conditional operator. It basically means:

"Evaluate the first operand; if that's null, stop, with a result of null. Otherwise, evaluate the second operand (as a member access of the first operand)."

In your example, the point is that if a is null, then a?.PropertyOfA will evaluate to null rather than throwing an exception - it will then compare that null reference with foo (using string's == overload), find they're not equal and execution will go into the body of the if statement.

In other words, it's like this:

string bar = (a == null ? null : a.PropertyOfA);
if (bar != foo)
{
    ...
}

... except that a is only evaluated once.

Note that this can change the type of the expression, too. For example, consider FileInfo.Length. That's a property of type long, but if you use it with the null conditional operator, you end up with an expression of type long?:

FileInfo fi = ...; // fi could be null
long? length = fi?.Length; // If fi is null, length will be null

Start an activity from a fragment

If you are using getActivity() then you have to make sure that the calling activity is added already. If activity has not been added in such case so you may get null when you call getActivity()

in such cases getContext() is safe

then the code for starting the activity will be slightly changed like,

Intent intent = new Intent(getContext(), mFragmentFavorite.class);
startActivity(intent);

Activity, Service and Application extends ContextWrapper class so you can use this or getContext() or getApplicationContext() in the place of first argument.

How to change Java version used by TOMCAT?

If you use the standard scripts to launch Tomcat (i.e. you haven't installed Tomcat as a windows service), you can use the setenv.bat file, to set your JRE_HOME version.

On Windows, create the file %CATALINA_BASE%\bin\setenv.bat, with content:

set "JRE_HOME=%ProgramFiles%\Java\jre1.6.0_20"

exit /b 0

And that should be it.

You can test this using %CATALINA_BASE%\bin\configtest.bat (Disclaimer: I've only checked this with a Tomcat7 installation).

Further Reading:

Use .corr to get the correlation between two columns

When you call this:

data = Top15[['Citable docs per Capita','Energy Supply per Capita']]
correlation = data.corr(method='pearson')

Since, DataFrame.corr() function performs pair-wise correlations, you have four pair from two variables. So, basically you are getting diagonal values as auto correlation (correlation with itself, two values since you have two variables), and other two values as cross correlations of one vs another and vice versa.

Either perform correlation between two series to get a single value:

from scipy.stats.stats import pearsonr
docs_col = Top15['Citable docs per Capita'].values
energy_col = Top15['Energy Supply per Capita'].values
corr , _ = pearsonr(docs_col, energy_col)

or, if you want a single value from the same function (DataFrame's corr):

single_value = correlation[0][1] 

Hope this helps.

Remote desktop connection protocol error 0x112f

This error may be triggered by insufficient memory on RDP server.

After few tries with this error, RDP managed to get a connection to the server and I was able to stop a bogus service consuming too much memory. This can be done also with sysinternals or sc.

How to select a directory and store the location using tkinter in Python

This code may be helpful for you.

from tkinter import filedialog
from tkinter import *
root = Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

Hibernate Auto Increment ID

If you have a numeric column that you want to auto-increment, it might be an option to set columnDefinition directly. This has the advantage, that the schema auto-generates the value even if it is used without hibernate. This might make your code db-specific though:

import javax.persistence.Column;
@Column(columnDefinition = "serial") // postgresql

How to programmatically move, copy and delete files and directories on SD?

To move a file this api can be used but you need atleat 26 as api level -

move file

But if you want to move directory no support is there so this native code can be used

    import org.apache.commons.io.FileUtils;

    import java.io.IOException;
    import java.io.File;

    public class FileModule {

    public void moveDirectory(String src, String des) {
    File srcDir = new File(src);
    File destDir = new File(des);
     try {
        FileUtils.moveDirectory(srcDir,destDir);
    } catch (Exception e) {
      Log.e("Exception" , e.toString());
      }
    }

    public void deleteDirectory(String dir) {
      File delDir = new File(dir);
      try {
        FileUtils.deleteDirectory(delDir);
       } catch (IOException e) {
      Log.e("Exception" , e.toString());
      }
     }
    }

How to obtain Telegram chat_id for a specific user?

Using the Perl API you can get it this way: first you send a message to the bot from Telegram, then issue a getUpdates and the chat id must be there:

#!/usr/bin/perl

use Data::Dumper;
use WWW::Telegram::BotAPI;

my $TOKEN = 'blablabla';
my $api = WWW::Telegram::BotAPI->new (
    token => $TOKEN
) or die "I can't connect";

my $out = $api->api_request ('getUpdates');
warn Dumper($out);
my $chat_id = $out->{result}->[0]->{message}->{chat}->{id};
print "chat_id=$chat_id\n";

The id should be in chat_id but it may depend of the result, so I also added a dump of the whole result.

You can install the Perl API from https://github.com/Robertof/perl-www-telegram-botapi. It depends on your system but I installed easily running this on my Linux server:

$ sudo cpan WWW::Telegram::BotAPI

Hope this helps

String.Format alternative in C++

The C++ way would be to use a std::stringstream object as:

std::stringstream fmt;
fmt << a << " " << b << " > " << c;

The C way would be to use sprintf.

The C way is difficult to get right since:

  • It is type unsafe
  • Requires buffer management

Of course, you may want to fall back on the C way if performance is an issue (imagine you are creating fixed-size million little stringstream objects and then throwing them away).

Python using enumerate inside list comprehension

Be explicit about the tuples.

[(i, j) for (i, j) in enumerate(mylist)]

Facebook user url by id

As of now (NOV-2019), graph.api V5.0

graph API says, refer graph api

A link to the person's Timeline. The link will only resolve if the person clicking the link is logged into Facebook and is a friend of the person whose profile is being viewed.

doc

Arguments to main in C

Main is just like any other function and argc and argv are just like any other function arguments, the difference is that main is called from C Runtime and it passes the argument to main, But C Runtime is defined in c library and you cannot modify it, So if we do execute program on shell or through some IDE, we need a mechanism to pass the argument to main function so that your main function can behave differently on the runtime depending on your parameters. The parameters are argc , which gives the number of arguments and argv which is pointer to array of pointers, which holds the value as strings, this way you can pass any number of arguments without restricting it, it's the other way of implementing var args.

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

jQuery get the rendered height of an element?

document.querySelector('.project_list_div').offsetHeight;

Update Angular model after setting input value with jQuery

ngModel listens for "input" event, so to "fix" your code you'd need to trigger that event after setting the value:

$('button').click(function(){
    var input = $('input');
    input.val('xxx');
    input.trigger('input'); // Use for Chrome/Firefox/Edge
    input.trigger('change'); // Use for Chrome/Firefox/Edge + IE11
});

For the explanation of this particular behaviour check out this answer that I gave a while ago: "How does AngularJS internally catch events like 'onclick', 'onchange'?"


But unfortunately, this is not the only problem you have. As pointed out with other post comments, your jQuery-centric approach is plain wrong. For more info take a look at this post: How do I “think in AngularJS” if I have a jQuery background?).

Eclipse: Frustration with Java 1.7 (unbound library)

Have you actually downloaded and installed one of the milestone builds from https://jdk7.dev.java.net/ ?

You can have a play with the features, though it's not stable so you shouldn't be releasing software against them.

How do you push a tag to a remote repository using Git?

To push specific, one tag do following git push origin tag_name

How can I set the background color of <option> in a <select> element?

Just like normal background-color: #f0f

You just need a way to target it, eg: <option id="myPinkOption">blah</option>

How to compare dates in datetime fields in Postgresql?

When you compare update_date >= '2013-05-03' postgres casts values to the same type to compare values. So your '2013-05-03' was casted to '2013-05-03 00:00:00'.

So for update_date = '2013-05-03 14:45:00' your expression will be that:

'2013-05-03 14:45:00' >= '2013-05-03 00:00:00' AND '2013-05-03 14:45:00' <= '2013-05-03 00:00:00'

This is always false

To solve this problem cast update_date to date:

select * from table where update_date::date >= '2013-05-03' AND update_date::date <= '2013-05-03' -> Will return result

sort json object in javascript

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

Convert String value format of YYYYMMDDHHMMSS to C# DateTime

class Program
{
    static void Main(string[] args)
    {

        int transactionDate = 20201010;
        int? transactionTime = 210000;

        var agreementDate = DateTime.Today;
        var previousDate = agreementDate.AddDays(-1);

        var agreementHour = 22;
        var agreementMinute = 0;
        var agreementSecond = 0;

        var startDate = new DateTime(previousDate.Year, previousDate.Month, previousDate.Day, agreementHour, agreementMinute, agreementSecond);
        var endDate = new DateTime(agreementDate.Year, agreementDate.Month, agreementDate.Day, agreementHour, agreementMinute, agreementSecond);

        DateTime selectedDate = Convert.ToDateTime(transactionDate.ToString().Substring(6, 2) + "/" + transactionDate.ToString().Substring(4, 2) + "/" + transactionDate.ToString().Substring(0, 4) + " " + string.Format("{0:00:00:00}", transactionTime));

        Console.WriteLine("Selected Date : " + selectedDate.ToString());
        Console.WriteLine("Start Date : " + startDate.ToString());
        Console.WriteLine("End Date : " + endDate.ToString());

        if (selectedDate > startDate && selectedDate <= endDate)
            Console.WriteLine("Between two dates..");
        else if (selectedDate <= startDate)
            Console.WriteLine("Less than or equal to the start date!");
        else if (selectedDate > endDate)
            Console.WriteLine("Greater than end date!");
        else
            Console.WriteLine("Out of date ranges!");
    }
}

Status bar and navigation bar appear over my view's bounds in iOS 7

If you want the view to have the translucent nav bar (which is kind of nice) you have to setup a contentInset or similar.

Here is how I do it:

// Check if we are running on ios7
if([[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0] intValue] >= 7) {
      CGRect statusBarViewRect = [[UIApplication sharedApplication] statusBarFrame];
      float heightPadding = statusBarViewRect.size.height+self.navigationController.navigationBar.frame.size.height;

      myContentView.contentInset = UIEdgeInsetsMake(heightPadding, 0.0, 0.0, 0.0);
}

Get size of folder or file

You need FileUtils#sizeOfDirectory(File) from commons-io.

Note that you will need to manually check whether the file is a directory as the method throws an exception if a non-directory is passed to it.

WARNING: This method (as of commons-io 2.4) has a bug and may throw IllegalArgumentException if the directory is concurrently modified.

How to convert View Model into JSON object in ASP.NET MVC?

Well done, you've only just started using MVC and you've found its first major flaw.

You don't really want to be converting it to JSON in the view, and you don't really want to convert it in the controller, as neither of these locations make sense. Unfortunately, you're stuck with this situation.

The best thing I've found to do is send the JSON to the view in a ViewModel, like this:

var data = somedata;
var viewModel = new ViewModel();
var serializer = new JavaScriptSerializer();
viewModel.JsonData = serializer.Serialize(data);

return View("viewname", viewModel);

then use

<%= Model.JsonData %>

in your view. Be aware that the standard .NET JavaScriptSerializer is pretty crap.

doing it in the controller at least makes it testable (although not exactly like the above - you probably want to take an ISerializer as a dependency so you can mock it)

Update also, regarding your JavaScript, it would be good practice to wrap ALL the widget JS you have above like so:

(
    // all js here
)();

this way if you put multiple widgets on a page, you won't get conflicts (unless you need to access the methods from elsewhere in the page, but in that case you should be registering the widget with some widget framework anyway). It may not be a problem now, but it would be good practice to add the brackets now to save yourself muchos effort in the future when it becomes a requirement, it's also good OO practice to encapsulate the functionality.

Call JavaScript function on DropDownList SelectedIndexChanged Event:

You can use the ScriptManager.RegisterStartupScript(); to call any of your javascript event/Client Event from the server. For example, to display a message using javascript's alert();, you can do this:

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
Response.write("<script>alert('This is my message');</script>");
 //----or alternatively and to be more proper
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "alert('This is my message')", true);
}

To be exact for you, do this...

protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
 ScriptManager.RegisterStartupScript(this, this.GetType(), "callJSFunction", "CalcTotalAmt();", true);
}

What's the difference between a POST and a PUT HTTP REQUEST?

The request methods GET, PUT and DELETE are CRUD (create, read, update and delete) operations—that is data management operations—on the state of a target resource (the one identified by the request URI):

  • GET should read the state of the target resource;
  • PUT should create or update the state of the target resource;
  • DELETE should delete the state of the target resource.

The request method POST is a different beast. It should not create the state of the target resource like PUT because it is a process operation with a higher-level goal than CRUD (cf. RFC 7231, § 4.3.3). The process may create a resource but different from the target resource, otherwise the lower-level goal request method PUT should be used, so even in this case that does not make it a CRUD operation.

The difference between CRUD operations (GET, PUT and DELETE in HTTP) and non-CRUD operations (POST in HTTP) is the difference between abstract data types and objects that Alan Kay was stressing in most of his talks and his ACM paper The Early History of Smalltalk:

What I got from Simula was that you could now replace bindings and assignments with goals. The last thing you wanted any programmer to do is mess with internal state even if presented figuratively. Instead, the objects should be presented as sites of higher level behaviors more appropriate for use as dynamic components.

[…] It is unfortunate that much of what is called "object-oriented programming" today is simply old style programming with fancier constructs. Many programs are loaded with "assignment-style" operations now done by more expensive attached procedures.

[…] Assignment statements—even abstract ones—express very low-level goals, and more of them will be needed to get anything done. […] Another way to think of all this is: though the late-binding of automatic storage allocations doesn’t do anything a programmer can’t do, its presence leads both to simpler and more powerful code. OOP is a late binding strategy for many things and all of them together hold off fragility and size explosion much longer than the older methodologies.

How to use a dot "." to access members of dictionary?

I've always kept this around in a util file. You can use it as a mixin on your own classes too.

class dotdict(dict):
    """dot.notation access to dictionary attributes"""
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

mydict = {'val':'it works'}
nested_dict = {'val':'nested works too'}
mydict = dotdict(mydict)
mydict.val
# 'it works'

mydict.nested = dotdict(nested_dict)
mydict.nested.val
# 'nested works too'

How to select a value in dropdown javascript?

Instead of doing

function setSelectedIndex(s, v) {
    for ( var i = 0; i < s.options.length; i++ ) {
        if ( s.options[i].value == v ) {
            s.options[i].selected = true;
            return;
        }
    }
}

I solved this problem by doing this

function setSelectedValue(dropDownList, valueToSet) {
    var option = dropDownList.firstChild;
    for (var i = 0; i < dropDownList.length; i++) {
        if (option.text.trim().toLowerCase() == valueToSet.trim().toLowerCase()) {
            option.selected = true;
            return;
        }
        option = option.nextElementSibling;
    }
}

If you work with strings, you should use the .trim() method, sometimes blank spaces can cause trouble and they are hard to detect in javascript debugging sessions.

dropDownList.firstChild will actually be your first option tag. Then, by doing option.nextElementSibling you can go to the next option tag, so the next choice in your dropdownlist element. If you want to get the number of option tags you can use dropDownList.length which I used in the for loop.

Hope this helps someone.

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

What is "Connect Timeout" in sql server connection string?

That is the timeout to create the connection, NOT a timeout for commands executed over that connection.

See for instance http://www.connectionstrings.com/all-sql-server-connection-string-keywords/ (note that the property is "Connect Timeout" (or "Connection Timeout"), not just "Timeout")


From the comments:

It is not possible to set the command timeout through the connection string. However, the SqlCommand has a CommandTimeout property (derived from DbCommand) where you can set a timeout (in seconds) per command.

Do note that when you loop over query results with Read(), the timeout is reset on every read. The timeout is for each network request, not for the total connection.

How to write a std::string to a UTF-8 text file

What is the easiest and simple way to do so?

The most intuitive and thus easiest handling of utf8 in C++ is for sure using a drop-in replacement for std::string. As the internet still lacks of one, I went to implement the functionality on my own:

tinyutf8 (EDIT: now Github).

This library provides a very lightweight drop-in preplacement for std::string (or std::u32string if you will, because you iterate over codepoints rather that chars). Ity is implemented succesfully in the middle between fast access and small memory consumption, while being very robust. This robustness to 'invalid' UTF8-sequences makes it (nearly completely) compatible with ANSI (0-255).

Hope this helps!

How to refresh a Page using react-route Link

Try like this.

You must give a function as value to onClick()

You button:

<button type="button" onClick={ refreshPage }> <span>Reload</span> </button> 

refreshPage function:

function refreshPage(){ 
    window.location.reload(); 
}

Reading *.wav files in Python

If you want to procces an audio block by block, some of the given solutions are quite awful in the sense that they imply loading the whole audio into memory producing many cache misses and slowing down your program. python-wavefile provides some pythonic constructs to do NumPy block-by-block processing using efficient and transparent block management by means of generators. Other pythonic niceties are context manager for files, metadata as properties... and if you want the whole file interface, because you are developing a quick prototype and you don't care about efficency, the whole file interface is still there.

A simple example of processing would be:

import sys
from wavefile import WaveReader, WaveWriter

with WaveReader(sys.argv[1]) as r :
    with WaveWriter(
            'output.wav',
            channels=r.channels,
            samplerate=r.samplerate,
            ) as w :

        # Just to set the metadata
        w.metadata.title = r.metadata.title + " II"
        w.metadata.artist = r.metadata.artist

        # This is the prodessing loop
        for data in r.read_iter(size=512) :
            data[1] *= .8     # lower volume on the second channel
            w.write(data)

The example reuses the same block to read the whole file, even in the case of the last block that usually is less than the required size. In this case you get an slice of the block. So trust the returned block length instead of using a hardcoded 512 size for any further processing.

Disable and enable buttons in C#

Change this

button2.Enabled == true

to

button2.Enabled = true;

"The breakpoint will not currently be hit. The source code is different from the original version." What does this mean?

go to:

Tools > Options > Debugging > General > unchecked "Require source files to exactly match the original version"

How to delete rows from a pandas DataFrame based on a conditional expression

If you want to drop rows of data frame on the basis of some complicated condition on the column value then writing that in the way shown above can be complicated. I have the following simpler solution which always works. Let us assume that you want to drop the column with 'header' so get that column in a list first.

text_data = df['name'].tolist()

now apply some function on the every element of the list and put that in a panda series:

text_length = pd.Series([func(t) for t in text_data])

in my case I was just trying to get the number of tokens:

text_length = pd.Series([len(t.split()) for t in text_data])

now add one extra column with the above series in the data frame:

df = df.assign(text_length = text_length .values)

now we can apply condition on the new column such as:

df = df[df.text_length  >  10]
def pass_filter(df, label, length, pass_type):

    text_data = df[label].tolist()

    text_length = pd.Series([len(t.split()) for t in text_data])

    df = df.assign(text_length = text_length .values)

    if pass_type == 'high':
        df = df[df.text_length  >  length]

    if pass_type == 'low':
        df = df[df.text_length  <  length]

    df = df.drop(columns=['text_length'])

    return df

What is a difference between unsigned int and signed int in C?

Here is the very nice link which explains the storage of signed and unsigned INT in C -

http://answers.yahoo.com/question/index?qid=20090516032239AAzcX1O

Taken from this above article -

"process called two's complement is used to transform positive numbers into negative numbers. The side effect of this is that the most significant bit is used to tell the computer if the number is positive or negative. If the most significant bit is a 1, then the number is negative. If it's 0, the number is positive."

Should I use Java's String.format() if performance is important?

In your example, performance probalby isn't too different but there are other issues to consider: namely memory fragmentation. Even concatenate operation is creating a new string, even if its temporary (it takes time to GC it and it's more work). String.format() is just more readable and it involves less fragmentation.

Also, if you're using a particular format a lot, don't forget you can use the Formatter() class directly (all String.format() does is instantiate a one use Formatter instance).

Also, something else you should be aware of: be careful of using substring(). For example:

String getSmallString() {
  String largeString = // load from file; say 2M in size
  return largeString.substring(100, 300);
}

That large string is still in memory because that's just how Java substrings work. A better version is:

  return new String(largeString.substring(100, 300));

or

  return String.format("%s", largeString.substring(100, 300));

The second form is probably more useful if you're doing other stuff at the same time.

Sending email with PHP from an SMTP server

The problem is that PHP mail() function has a very limited functionality. There are several ways to send mail from PHP.

  1. mail() uses SMTP server on your system. There are at least two servers you can use on Windows: hMailServer and xmail. I spent several hours configuring and getting them up. First one is simpler in my opinion. Right now, hMailServer is working on Windows 7 x64.
  2. mail() uses SMTP server on remote or virtual machine with Linux. Of course, real mail service like Gmail doesn't allow direct connection without any credentials or keys. You can set up virtual machine or use one located in your LAN. Most linux distros have mail server out of the box. Configure it and have fun. I use default exim4 on Debian 7 that listens its LAN interface.
  3. Mailing libraries use direct connections. Libs are easier to set up. I used SwiftMailer and it perfectly sends mail from Gmail account. I think that PHPMailer is pretty good too.

No matter what choice is your, I recommend you use some abstraction layer. You can use PHP library on your development machine running Windows and simply mail() function on production machine with Linux. Abstraction layer allows you to interchange mail drivers depending on system which your application is running on. Create abstract MyMailer class or interface with abstract send() method. Inherit two classes MyPhpMailer and MySwiftMailer. Implement send() method in appropriate ways.

Overflow:hidden dots at the end

Hopefully it's helpful for you:

_x000D_
_x000D_
.text-with-dots {_x000D_
    display: block;_x000D_
    max-width: 98%;_x000D_
    white-space: nowrap;_x000D_
    overflow: hidden !important;_x000D_
    text-overflow: ellipsis;_x000D_
}
_x000D_
<div class='text-with-dots'>Some texts here Some texts here Some texts here Some texts here Some texts here Some texts here </div>
_x000D_
_x000D_
_x000D_

How to position two divs horizontally within another div

I agree with Darko Z on applying "overflow: hidden" to #sub-title. However, it should be mentioned that the overflow:hidden method of clearing floats does not work with IE6 unless you have a specified width or height. Or, if you don't want to specify a width or height, you can use "zoom: 1":

#sub-title { overflow:hidden; zoom: 1; }

How to convert date to timestamp?

The below code will convert the current date into the timestamp.

var currentTimeStamp = Date.parse(new Date());
console.log(currentTimeStamp);

C compiler for Windows?

Must Windows C++ compilers will work.

Also, check out MinGW.

What is a "bundle" in an Android application

Bundles are generally used for passing data between various Android activities. It depends on you what type of values you want to pass, but bundles can hold all types of values and pass them to the new activity.

You can use it like this:

Intent intent = new...
Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("myKey", AnyValue);  
startActivity(intent);

You can get the passed values by doing:

Bundle extras = intent.getExtras(); 
String tmp = extras.getString("myKey");

You can find more info at:

Is there a way to SELECT and UPDATE rows at the same time?

I have faced the same issue; I have to update the credit amount, and have to get modified time, along with credit details from DB. It is basically

SYNCHRONOUSLY/ATOMICALLY perform (UPDATE then GET) in MYSQL

I have tried many options and found one that solved my issue.

1) OPTION_1 SELECT FOR UPDATE

This is maintaining the lock till update (SYNC from GET to UPDATE), but i need lock after update till the GET.

2) OPTION_2 Stored procedure

Stored procedure will not execute synchronously like redis lua, So there also we need sync code to perform that.

3) OPTION_3 Transaction

I have used JPA entityManager like below, thought that before commit no one can update, and before commit i will get the updated object along with modified time (from DB). But i didn't get the latest object. Only commit i got the latest.

    try {
        entityManager.getTransaction().begin();
        //entityManager.persist(object);
        int upsert = entityManager.createNativeQuery(
        "update com.bill.Credit c set c.balance = c.balance - ?1
          where c.accountId = ?2 and c.balance >= ?1").executeUpdate(); 
             //c.balance >= ? for limit check
        Credit newCredit = entityManager.find(Credit.class, "id");
        entityManager.refresh(newCredit); //SHOULD GET LATEST BUT NOT
        entityManager.getTransaction().commit();
    } finally {     
        entityManager.unwrap(Session.class).close();
    } 

4) OPTION_4 LOCK solved the issue, so before update i acquired the lock; then after GET i have released the lock.

private Object getLock(final EntityManager entityManager, final String Id){

    entityManager.getTransaction().begin();
    Object obj_acquire = entityManager.createNativeQuery("SELECT GET_LOCK('" + Id + "', 10)").getSingleResult();
    entityManager.getTransaction().commit();
    return obj_acquire;
}


private Object releaseLock(final EntityManager entityManager, final String Id){

    entityManager.getTransaction().begin();
    Object obj_release = entityManager.createNativeQuery("SELECT RELEASE_LOCK('" + Id + "')").getSingleResult();
    entityManager.getTransaction().commit();
    return obj_release;
}

Format string to a 3 digit number

(Can't comment yet with enough reputation , let me add a sidenote)

Just in case your output need to be fixed length of 3-digit , i.e. for number run up to 1000 or more (reserved fixed length), don't forget to add mod 1000 on it .

yourNumber=1001;
yourString= yourNumber.ToString("D3");        // "1001" 
yourString= (yourNumber%1000).ToString("D3"); // "001" truncated to 3-digit as expected

Trail sample on Fiddler https://dotnetfiddle.net/qLrePt

jQuery preventDefault() not triggered

i just had the same problems - have been testing a lot of different stuff. but it just wouldn't work. then i checked the tutorial examples on jQuery.com again and found out:

your jQuery script needs to be after the elements you are referring to !

so your script needs to be after the html-code you want to access!

seems like jQuery can't access it otherwise.

How to redirect to action from JavaScript method?

I struggled with this a little because I wanted to use Knockout to bind the button to the click event. Here's my button and the relevant function from inside my view model.

<a class="btn btn-secondary showBusy" data-bind="click: back">Back to Dashboard</a>

var vm = function () {
...
    self.back = function() {
        window.location.href = '@Url.Action("LicenseDashboard", "Application")';
    }
}

error: strcpy was not declared in this scope

Observations:

  • #include <cstring> should introduce std::strcpy().
  • using namespace std; (as written in medico.h) introduces any identifiers from std:: into the global namespace.

Aside from using namespace std; being somewhat clumsy once the application grows larger (as it introduces one hell of a lot of identifiers into the global namespace), and that you should never use using in a header file (see below!), using namespace does not affect identifiers introduced after the statement.

(using namespace std is written in the header, which is included in medico.cpp, but #include <cstring> comes after that.)

My advice: Put the using namespace std; (if you insist on using it at all) into medico.cpp, after any includes, and use explicit std:: in medico.h.


strcmpi() is not a standard function at all; while being defined on Windows, you have to solve case-insensitive compares differently on Linux.

(On general terms, I would like to point to this answer with regards to "proper" string handling in C and C++ that takes Unicode into account, as every application should. Summary: The standard cannot handle these things correctly; do use ICU.)


warning: deprecated conversion from string constant to ‘char*’

A "string constant" is when you write a string literal (e.g. "Hello") in your code. Its type is const char[], i.e. array of constant characters (as you cannot change the characters). You can assign an array to a pointer, but assigning to char *, i.e. removing the const qualifier, generates the warning you are seeing.


OT clarification: using in a header file changes visibility of identifiers for anyone including that header, which is usually not what the user of your header file wants. For example, I could use std::string and a self-written ::string just perfectly in my code, unless I include your medico.h, because then the two classes will clash.

Don't use using in header files.

And even in implementation files, it can introduce lots of ambiguity. There is a case to be made to use explicit namespacing in implementation files as well.

Error: 10 $digest() iterations reached. Aborting! with dynamic sortby predicate

Please check this jsFiddle. (The code is basically the same you posted but I use an element instead of the window to bind the scroll events).

As far as I can see, there is no problem with the code you posted. The error you mentioned normally occurs when you create a loop of changes over a property. For example, like when you watch for changes on a certain property and then change the value of that property on the listener:

$scope.$watch('users', function(value) {
  $scope.users = [];
});

This will result on an error message:

Uncaught Error: 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: ...

Make sure that your code doesn't have this kind of situations.

update:

This is your problem:

<div ng-init="user.score=user.id+1"> 

You shouldn't change objects/models during the render or otherwise, it will force a new render (and consequently a loop, which causes the 'Error: 10 $digest() iterations reached. Aborting!').

If you want to update the model, do it on the Controller or on a Directive, never on the view. angularjs documentation recommends not to use the ng-init exactly to avoid these kinds of situations:

Use ngInit directive in templates (for toy/example apps only, not recommended for real applications)

Here's a jsFiddle with a working example.

Passing bash variable to jq

Jq now have better way to acces environment variables, you can use env.EMAILI:

projectID=$(cat file.json | jq -r ".resource[] | select(.username==env.EMAILID) | .id")

Java: Finding the highest value in an array

If you don't want to use any java predefined libraries then below is the

simplest way

   public class Test {

    public static void main(String[] args) {
        double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
            8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
            3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};

        double maxx = decMax[0];

        for (int i = 0; i < decMax.length; i++) {
            if (maxx < decMax[i]) {
                maxx = decMax[i];
            }
        }
        System.out.println(maxx);

    }
}

Get error message if ModelState.IsValid fails?

You can do this in your view without doing anything special in your action by using Html.ValidationSummary() to show all error messages, or Html.ValidationMessageFor() to show a message for a specific property of the model.

If you still need to see the errors from within your action or controller, see the ModelState.Errors property

Can a class member function template be virtual?

There is a workaround for 'virtual template method' if set of types for the template method is known in advance.

To show the idea, in the example below only two types are used (int and double).

There, a 'virtual' template method (Base::Method) calls corresponding virtual method (one of Base::VMethod) which, in turn, calls template method implementation (Impl::TMethod).

One only needs to implement template method TMethod in derived implementations (AImpl, BImpl) and use Derived<*Impl>.

class Base
{
public:
    virtual ~Base()
    {
    }

    template <typename T>
    T Method(T t)
    {
        return VMethod(t);
    }

private:
    virtual int VMethod(int t) = 0;
    virtual double VMethod(double t) = 0;
};

template <class Impl>
class Derived : public Impl
{
public:
    template <class... TArgs>
    Derived(TArgs&&... args)
        : Impl(std::forward<TArgs>(args)...)
    {
    }

private:
    int VMethod(int t) final
    {
        return Impl::TMethod(t);
    }

    double VMethod(double t) final
    {
        return Impl::TMethod(t);
    }
};

class AImpl : public Base
{
protected:
    AImpl(int p)
        : i(p)
    {
    }

    template <typename T>
    T TMethod(T t)
    {
        return t - i;
    }

private:
    int i;
};

using A = Derived<AImpl>;

class BImpl : public Base
{
protected:
    BImpl(int p)
        : i(p)
    {
    }

    template <typename T>
    T TMethod(T t)
    {
        return t + i;
    }

private:
    int i;
};

using B = Derived<BImpl>;

int main(int argc, const char* argv[])
{
    A a(1);
    B b(1);
    Base* base = nullptr;

    base = &a;
    std::cout << base->Method(1) << std::endl;
    std::cout << base->Method(2.0) << std::endl;

    base = &b;
    std::cout << base->Method(1) << std::endl;
    std::cout << base->Method(2.0) << std::endl;
}

Output:

0
1
2
3

NB: Base::Method is actually surplus for real code (VMethod can be made public and used directly). I added it so it looks like as an actual 'virtual' template method.

Excel Date to String conversion

I have no idea about the year of publication of the question; it might be old now. So, I expect my answer to be more of a reference for future similar questions after my post.

I don't know if anybody out there has already given an answer similar to the one I am about to give, which might result -I think- being the simplest, most direct and most effective: If someone has already given it, I apologize, but I haven't seen it. Here, my answer using CStr instead of TEXT:

Asuming cell A1 contains a date, and using VBA code:

Dim strDate As String

'Convert to string the value contained in A1 (a date)
strDate = CStr([A1].Value)

You can, thereafter, manipulate it as any ordinary string using string functions (MID, LEFT, RIGHT, LEN, CONCATENATE (&), etc.)

How do I mount a host directory as a volume in docker compose

we have to create your own docker volume mapped with the host directory before we mention in the docker-compose.yml as external

1.Create volume named share

docker volume create --driver local \
--opt type=none \
--opt device=/home/mukundhan/share \
--opt o=bind share

2.Use it in your docker-compose

version: "3"

volumes:
  share:
    external: true

services:
  workstation:
    container_name: "workstation"
    image: "ubuntu"
    stdin_open: true
    tty: true
    volumes:
      - share:/share:consistent
      - ./source:/source:consistent
    working_dir: /source
    ipc: host
    privileged: true
    shm_size: '2gb'
  db:
    container_name: "db"
    image: "ubuntu"
    stdin_open: true
    tty: true
    volumes:
      - share:/share:consistent
    working_dir: /source
    ipc: host

This way we can share the same directory with many services running in different containers

Execute php file from another php

exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g

exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;

or use the punct at the top of your php script

#!/usr/local/bin/php
<?php ... ?>

Initialize class fields in constructor or at declaration?

In Java, an initializer with the declaration means the field is always initialized the same way, regardless of which constructor is used (if you have more than one) or the parameters of your constructors (if they have arguments), although a constructor might subsequently change the value (if it is not final). So using an initializer with a declaration suggests to a reader that the initialized value is the value that the field has in all cases, regardless of which constructor is used and regardless of the parameters passed to any constructor. Therefore use an initializer with the declaration only if, and always if, the value for all constructed objects is the same.

dyld: Library not loaded: @rpath/libswiftCore.dylib

To add on to the Enterprise distribution cert solution: you can open Keychain and inspect the cert. If there is any red text saying the trust chain can't be verified or it being revoked, it WILL NOT WORK! On my computer, our distribution cert was showing as revoked even though the web portal showed it as still valid. We got a new distribution cert, which was green (valid) in Keychain, and this solved the issue.

Converting a string to JSON object

JSON.parse() function will do.

or

Using Jquery,

var obj = jQuery.parseJSON( '{ "name": "Vinod" }' );
alert( obj.name === "Vinod" );

How to import jquery using ES6 syntax?

You can create a module converter like below:

// jquery.module.js
import 'https://code.jquery.com/jquery-3.3.1.min.js'
export default window.jQuery.noConflict(true)

This will remove global variables introduced by jQuery and export jQuery object as default.

Then use it in your script:

// script.js
import $ from "./jquery.module.js";

$(function(){
  $('body').text('youpi!');
});

Do not forget to load it as a module in your document:

<script type='module' src='./script.js'></script>

http://plnkr.co/edit/a59ETj3Yo2PJ0Aqkxbeu?p=preview

git stash apply version

Since version 2.11, it's pretty easy, you can use the N stack number instead of saying "stash@{n}". So now instead of using:

git stash apply "stash@{n}"

You can type:

git stash apply n

For example, in your list:

stash@{0}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{1}: WIP on design: f2c0c72... Adjust Password Recover Email
stash@{2}: WIP on design: eb65635... Email Adjust
stash@{3}: WIP on design: eb65635... Email Adjust

If you want to apply stash@{1} you could type:

git stash apply 1

Otherwise, you can use it even if you have some changes in your directory since 1.7.5.1, but you must be sure the stash won't overwrite your working directory changes if it does you'll get an error:

error: Your local changes to the following files would be overwritten by merge:
        file
Please commit your changes or stash them before you merge.

In versions prior to 1.7.5.1, it refused to work if there was a change in the working directory.


Git release notes:

The user always has to say "stash@{$N}" when naming a single element in the default location of the stash, i.e. reflogs in refs/stash. The "git stash" command learned to accept "git stash apply 4" as a short-hand for "git stash apply stash@{4}"

git stash apply" used to refuse to work if there was any change in the working tree, even when the change did not overlap with the change the stash recorded

How do I clone a subdirectory only of a Git repository?

Git 1.7.0 has “sparse checkouts”. See “core.sparseCheckout” in the git config manpage, “Sparse checkout” in the git read-tree manpage, and “Skip-worktree bit” in the git update-index manpage.

The interface is not as convenient as SVN’s (e.g. there is no way to make a sparse checkout at the time of an initial clone), but the base functionality upon which simpler interfaces could be built is now available.

CheckBox in RecyclerView keeps on checking different items

That's an expected behavior. You are not setting your checkbox selected or not. You are selecting one and View holder keeps it selected. You can add a boolean variable into your ObjectIncome object and keep your item's selection status.

You may look at my example. You can do something like that:

public class AdapterTrashIncome extends RecyclerView.Adapter<AdapterTrashIncome.ViewHolder> {

    private ArrayList<ObjectIncome> myItems = new ArrayList<>();

    public AdapterTrashIncome(ArrayList<ObjectIncome> getItems, Context context){
        try {
            mContext = context;
            myItems = getItems;
            }catch (Exception e){
            Log.e(FILE_NAME, "51: " + e.toString());
            e.printStackTrace();
        }
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tvContent;
        public CheckBox cbSelect;

        public ViewHolder(View v) {
            super(v);
            tvContent = (TextView) v.findViewById(R.id.tvContent);
            cbSelect = (CheckBox) v.findViewById(R.id.cbSelect);
        }
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, final int position) {
        final ObjectIncome objIncome = myItems.get(position);
        String content = "<b>lalalla</b>";
        holder.tvContent.setText(Html.fromHtml(content));

        //in some cases, it will prevent unwanted situations
        holder.cbSelect.setOnCheckedChangeListener(null);

        //if true, your checkbox will be selected, else unselected
        holder.cbSelect.setChecked(objIncome.isSelected());

        holder.cbSelect.setOnCheckedChangeListener(new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    //set your object's last status
                    objIncome.setSelected(isChecked);
            }
        });

    }
}

Download file using libcurl in C/C++

The example you are using is wrong. See the man page for easy_setopt. In the example write_data uses its own FILE, *outfile, and not the fp that was specified in CURLOPT_WRITEDATA. That's why closing fp causes problems - it's not even opened.

This is more or less what it should look like (no libcurl available here to test)

#include <stdio.h>
#include <curl/curl.h>
/* For older cURL versions you will also need 
#include <curl/types.h>
#include <curl/easy.h>
*/
#include <string>

size_t write_data(void *ptr, size_t size, size_t nmemb, FILE *stream) {
    size_t written = fwrite(ptr, size, nmemb, stream);
    return written;
}

int main(void) {
    CURL *curl;
    FILE *fp;
    CURLcode res;
    char *url = "http://localhost/aaa.txt";
    char outfilename[FILENAME_MAX] = "C:\\bbb.txt";
    curl = curl_easy_init();
    if (curl) {
        fp = fopen(outfilename,"wb");
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
        res = curl_easy_perform(curl);
        /* always cleanup */
        curl_easy_cleanup(curl);
        fclose(fp);
    }
    return 0;
}

Updated: as suggested by @rsethc types.h and easy.h aren't present in current cURL versions anymore.

Reading a file line by line in Go

In Go 1.1 and newer the most simple way to do this is with a bufio.Scanner. Here is a simple example that reads lines from a file:

package main

import (
    "bufio"
    "fmt"
    "log"
    "os"
)

func main() {
    file, err := os.Open("/path/to/file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}

This is the cleanest way to read from a Reader line by line.

There is one caveat: Scanner does not deal well with lines longer than 65536 characters. If that is an issue for you then then you should probably roll your own on top of Reader.Read().

How to run Linux commands in Java?

You can call run-time commands from java for both Windows and Linux.

import java.io.*;

public class Test{
   public static void main(String[] args) 
   {
            try
            { 
            Process process = Runtime.getRuntime().exec("pwd"); // for Linux
            //Process process = Runtime.getRuntime().exec("cmd /c dir"); //for Windows

            process.waitFor();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
               while ((line=reader.readLine())!=null)
               {
                System.out.println(line);   
                }
             }       
                catch(Exception e)
             { 
                 System.out.println(e); 
             }
             finally
             {
               process.destroy();
             }  
    }
}

Hope it Helps.. :)

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

Had this issue when provisioning a new site for VVV in vvv-config.yml with a faulty syntax, vagrant up would throw the error. Deleting and reverting to old configuration, running vagrant provision helped

How can I render repeating React elements?

You can put expressions inside braces. Notice in the compiled JavaScript why a for loop would never be possible inside JSX syntax; JSX amounts to function calls and sugared function arguments. Only expressions are allowed.

(Also: Remember to add key attributes to components rendered inside loops.)

JSX + ES2015:

render() {
  return (
    <table className="MyClassName">
      <thead>
        <tr>
          {this.props.titles.map(title =>
            <th key={title}>{title}</th>
          )}
        </tr>
      </thead>
      <tbody>
        {this.props.rows.map((row, i) =>
          <tr key={i}>
            {row.map((col, j) =>
              <td key={j}>{col}</td>
            )}
          </tr>
        )}
      </tbody>
    </table>
  );
} 

JavaScript:

render: function() {
  return (
    React.DOM.table({className: "MyClassName"}, 
      React.DOM.thead(null, 
        React.DOM.tr(null, 
          this.props.titles.map(function(title) {
            return React.DOM.th({key: title}, title);
          })
        )
      ), 
      React.DOM.tbody(null, 
        this.props.rows.map(function(row, i) {
          return (
            React.DOM.tr({key: i}, 
              row.map(function(col, j) {
                return React.DOM.td({key: j}, col);
              })
            )
          );
        })
      )
    )
  );
} 

How to configure XAMPP to send mail from localhost?

Its very simple to send emails on localhost or local server

Note: I am using the test mail server software on Windows 7 64bit with Xampp installed

Just download test mail server tool and install according to the instruction given on its website Test Mail Server Tool

Now you need to change only two lines under php.ini file

  1. Find [mail function] and remove semi colon which is before ;smtp = localhost
  2. Put the semi colon before sendmail_path = "C:\xampp\mailtodisk\mailtodisk.exe"

You don't need to change anything else, but if you still not getting emails than check for the SMTP port, the port number must be same.

The above method is for default settings provided by the Xampp software.

onClick not working on mobile (touch)

you can use instead of click :

$('#whatever').on('touchstart click', function(){ /* do something... */ });

Implement touch using Python?

Here's some code that uses ctypes (only tested on Linux):

from ctypes import *
libc = CDLL("libc.so.6")

#  struct timespec {
#             time_t tv_sec;        /* seconds */
#             long   tv_nsec;       /* nanoseconds */
#         };
# int futimens(int fd, const struct timespec times[2]);

class c_timespec(Structure):
    _fields_ = [('tv_sec', c_long), ('tv_nsec', c_long)]

class c_utimbuf(Structure):
    _fields_ = [('atime', c_timespec), ('mtime', c_timespec)]

utimens = CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf))
futimens = CFUNCTYPE(c_int, c_char_p, POINTER(c_utimbuf)) 

# from /usr/include/i386-linux-gnu/bits/stat.h
UTIME_NOW  = ((1l << 30) - 1l)
UTIME_OMIT = ((1l << 30) - 2l)
now  = c_timespec(0,UTIME_NOW)
omit = c_timespec(0,UTIME_OMIT)

# wrappers
def update_atime(fileno):
        assert(isinstance(fileno, int))
        libc.futimens(fileno, byref(c_utimbuf(now, omit)))
def update_mtime(fileno):
        assert(isinstance(fileno, int))
        libc.futimens(fileno, byref(c_utimbuf(omit, now)))

# usage example:
#
# f = open("/tmp/test")
# update_mtime(f.fileno())

How can I get relative path of the folders in my android project?

Generally we want to add images, txt, doc and etc files inside our Java project and specific folder such as /images. I found in search that in JAVA, we can get path from Root to folder which we specify as,

String myStorageFolder= "/images"; // this is folder name in where I want to store files.

String getImageFolderPath= request.getServletContext().getRealPath(myStorageFolder);

Here, request is object of HttpServletRequest. It will get the whole path from Root to /images folder. You will get output like,

C:\Users\STARK\Workspaces\MyEclipse.metadata.me_tcat7\webapps\JavaProject\images

Redirecting to a new page after successful login

Try header("Location:home.php"); instead of showing $msg = 'Login Complete! Thanks'; Hope it'll help you.

Delete rows containing specific strings in R

This should do the trick:

df[- grep("REVERSE", df$Name),]

Or a safer version would be:

df[!grepl("REVERSE", df$Name),]

TypeScript, Looping through a dictionary

To loop over the key/values, use a for in loop:

for (let key in myDictionary) {
    let value = myDictionary[key];
    // Use `key` and `value`
}

jQuery DataTable overflow and text-wrapping issues

I faced the same problem of text wrapping, solved it by changing the css of table class in DT_bootstrap.css. I introduced last two css lines table-layout and word-break.

   table.table {
    clear: both;
    margin-bottom: 6px !important;
    max-width: none !important;
    table-layout: fixed;
    word-break: break-all;
   } 

Swap two variables without using a temporary variable

If you want to swap 2 string variables:

a = (a+b).Substring((b=a).Length);

An helper method accordingly:

public static class Foo {
    public static void SwapString (ref string a, ref string b) {
       a = (a+b).Substring((b=a).Length);
    }
}

Usage would be then:

string a="Test 1";
string b="Test 2";
Foo.SwapString(a, b);

How to get a tab character?

Try &emsp;

as per the docs :

The character entities &ensp; and &emsp; denote an en space and an em space respectively, where an en space is half the point size and an em space is equal to the point size of the current font. For fixed pitch fonts, the user agent can treat the en space as being equivalent to A space character, and the em space as being equuivalent to two space characters.

Docs link : https://www.w3.org/MarkUp/html3/specialchars.html

Simple way to find if two different lists contain exactly the same elements?

If you're using (or are happy to use) Apache Commons Collections, you can use CollectionUtils.isEqualCollection which "returns true iff the given Collections contain exactly the same elements with exactly the same cardinalities."

Remove all stylings (border, glow) from textarea

The glow effect is most-likely controlled by box-shadow. In addition to adding what Pavel said, you can add the box-shadow property for the different browser engines.

textarea {
    border: none;
    overflow: auto;
    outline: none;

    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;

    resize: none; /*remove the resize handle on the bottom right*/
}

You may also try adding !important to prioritize this CSS.

Datatables - Setting column width

I set the column widths in the HTML markup like so:

    <thead>
        <tr>

            <th style='width: 5%;'>ProjectId</th>
            <th style='width: 15%;'>Title</th>
            <th style='width: 40%;'>Abstract</th>
            <th style='width: 20%;'>Keywords</th>
            <th style='width: 10%;'>PaperName</th>
            <th style='width: 10%;'>PaperURL</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr id="@item.ID">
                <td>@item.ProjectId</td>
                <td>@item.Title</td>
                <td>@item.Abstract</td>
                <td>@item.Keywords</td>
                <td>@item.PaperName</td>
                <td>@item.PaperURL</td>
            </tr>
        }
    </tbody>
</table>

Matlab: Running an m-file from command-line

Since none of the answers has information about feeding input argument, it is important to add it here. After some research, I found this link

Feeding the arguments is very similar to how we run a Matlab function.

matlab -r 'try myfunction(argument1,argument2); catch; end; quit'

If you are somehow getting an argument from bash/terminal, you simply need to insert that into the bash command as:

matlab -r 'try myfunction($MY_BASH_ARG,argument2); catch; end; quit'

(This is after a couple of trial and error)

Use of for_each on map elements

Here is an example of how you can use for_each for a map.

std::map<int, int> map;

map.insert(std::pair<int, int>(1, 2));
map.insert(std::pair<int, int>(2, 4));
map.insert(std::pair<int, int>(3, 6));

auto f = [](std::pair<int,int> it) {std::cout << it.first + it.second << std::endl; };
std::for_each(map.begin(), map.end(), f);

Inserting a Python datetime.datetime object into MySQL

You are most likely getting the TypeError because you need quotes around the datecolumn value.

Try:

now = datetime.datetime(2009, 5, 5)

cursor.execute("INSERT INTO table (name, id, datecolumn) VALUES (%s, %s, '%s')",
               ("name", 4, now))

With regards to the format, I had success with the above command (which includes the milliseconds) and with:

now.strftime('%Y-%m-%d %H:%M:%S')

Hope this helps.

What does "|=" mean? (pipe equal operator)

You have already got sufficient answer for your question. But may be my answer help you more about |= kind of binary operators.

I am writing table for bitwise operators:
Following are valid:

----------------------------------------------------------------------------------------
Operator   Description                                   Example
----------------------------------------------------------------------------------------
|=        bitwise inclusive OR and assignment operator   C |= 2 is same as C = C | 2
^=        bitwise exclusive OR and assignment operator   C ^= 2 is same as C = C ^ 2
&=        Bitwise AND assignment operator                C &= 2 is same as C = C & 2
<<=       Left shift AND assignment operator             C <<= 2 is same as C = C << 2
>>=       Right shift AND assignment operator            C >>= 2 is same as C = C >> 2  
----------------------------------------------------------------------------------------

note all operators are binary operators.

Also Note: (for below points I wanted to add my answer)

  • >>> is bitwise operator in Java that is called Unsigned shift
    but >>>= not an operator in Java. >>>= operator

  • ~ is bitwise complement bits, 0 to 1 and 1 to 0 (Unary operator) but ~= not an operator.

  • Additionally, ! Called Logical NOT Operator, but != Checks if the value of two operands are equal or not, if values are not equal then condition becomes true. e.g. (A != B) is true. where as A=!B means if B is true then A become false (and if B is false then A become true).

side note: | is not called pipe, instead its called OR, pipe is shell terminology transfer one process out to next..

How to efficiently count the number of keys/properties of an object in JavaScript?

For those that have Ext JS 4 in their project you can do:

Ext.Object.getSize(myobj);

The advantage of this is that it'll work on all Ext compatible browsers (IE6-IE8 included), however, I believe the running time is no better than O(n) though, as with other suggested solutions.

Does uninstalling a package with "pip" also remove the dependent packages?

You may have a try for https://github.com/cls1991/pef. It will remove package with its all dependencies.

Fastest way to count number of occurrences in a Python list

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

It's probably optimized heavily at the C level.

Edit: I randomly generated a large list.

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

Edit edit: This could be done with collections.Counter

a = Counter(your_list)
print a['1']

Using the same list in my last timing example

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.

Here is some profiling

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

I was struggling with a similar problem yesterday. I already had a "working" solution using jQuery UI's draggable together with jQuery Touch Punch, which are mentioned in other answers. However, using this method was causing weird bugs in some Android devices for me, and therefore I decided to write a small jQuery plugin that can make HTML elements draggable by using touch events instead of using a method that emulates fake mouse events.

The result of this is jQuery Draggable Touch which is a simple jQuery plugin for making elements draggable, that has touch devices as it's main target by using touch events (like touchstart, touchmove, touchend, etc.). It still has a fallback that uses mouse events if the browser/device doesn't support touch events.

Why do we use __init__ in Python classes?

The __init__ function is setting up all the member variables in the class. So once your bicluster is created you can access the member and get a value back:

mycluster = bicluster(...actual values go here...)
mycluster.left # returns the value passed in as 'left'

Check out the Python Docs for some info. You'll want to pick up an book on OO concepts to continue learning.

Why is my Button text forced to ALL CAPS on Lollipop?

Using the android.support.v7.widget.AppCompatButton in the XML layout will allow you to avoid having to have a layout-21 or programmatically changing anything. Naturally this will also work with AppCompat v7 library.

<android.support.v7.widget.AppCompatButton
    android:id="@+id/btnOpenMainDemo"
    android:textAllCaps="false"
    style="@style/HGButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/btn_main_demo"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"/>

Hope this helps.

Need to get a string after a "word" in a string in c#

string originalSting = "This is my string";
string texttobesearched = "my";
string dataAfterTextTobeSearch= finalCommand.Split(new string[] { texttobesearched     }, StringSplitOptions.None).Last();
if(dataAfterTextobeSearch!=originalSting)
{
    //your action here if data is found
}
else
{
    //action if the data being searched was not found
}

UIButton Image + Text IOS

It's really simple,just add image to background of you button and give text to titlelabel of button for uicontrolstatenormal. That's it.

[btn setBackgroundImage:[UIImage imageNamed:@"img.png"] forState:UIControlStateNormal];
[btn setContentVerticalAlignment:UIControlContentVerticalAlignmentBottom];
[btn setTitle:@"Click Me" forState:UIControlStateNormal];

How do I temporarily disable triggers in PostgreSQL?

For disable trigger

ALTER TABLE table_name DISABLE TRIGGER trigger_name

For enable trigger

ALTER TABLE table_name ENABLE TRIGGER trigger_name

In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?

This solution is a little older school, and should be memory efficient.

public static String toHexString(byte bytes[]) {
    if (bytes == null) {
        return null;
    }

    StringBuffer sb = new StringBuffer();
    for (int iter = 0; iter < bytes.length; iter++) {
        byte high = (byte) ( (bytes[iter] & 0xf0) >> 4);
        byte low =  (byte)   (bytes[iter] & 0x0f);
        sb.append(nibble2char(high));
        sb.append(nibble2char(low));
    }

    return sb.toString();
}

private static char nibble2char(byte b) {
    byte nibble = (byte) (b & 0x0f);
    if (nibble < 10) {
        return (char) ('0' + nibble);
    }
    return (char) ('a' + nibble - 10);
}

Best way to remove from NSMutableArray while iterating?

Nowadays you can use reversed block-based enumeration. A simple example code:

NSMutableArray *array = [@[@{@"name": @"a", @"shouldDelete": @(YES)},
                           @{@"name": @"b", @"shouldDelete": @(NO)},
                           @{@"name": @"c", @"shouldDelete": @(YES)},
                           @{@"name": @"d", @"shouldDelete": @(NO)}] mutableCopy];

[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if([obj[@"shouldDelete"] boolValue])
        [array removeObjectAtIndex:idx];
}];

Result:

(
    {
        name = b;
        shouldDelete = 0;
    },
    {
        name = d;
        shouldDelete = 0;
    }
)

another option with just one line of code:

[array filterUsingPredicate:[NSPredicate predicateWithFormat:@"shouldDelete == NO"]];

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

After a lot of trial and error I found this solved my problems. This is used to display photos on TVs via a browser.

  • It Keeps the photos aspect ratio
  • Scales in vertical and horizontal
  • Centers vertically and horizontal
  • The only thing to watch for are really wide images. They do stretch to fill, but not by much, standard camera photos are not altered.

    Give it a try :)

*only tested in chrome so far

HTML:

<div class="frame">
  <img src="image.jpg"/>
</div>

CSS:

.frame {
  border: 1px solid red;

  min-height: 98%;
  max-height: 98%;
  min-width: 99%;
  max-width: 99%;

  text-align: center;
  margin: auto;
  position: absolute;
}
img {
  border: 1px solid blue;

  min-height: 98%;
  max-width: 99%;
  max-height: 98%;

  width: auto;
  height: auto;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}

How to upload (FTP) files to server in a bash script?

The ftp command isn't designed for scripts, so controlling it is awkward, and getting its exit status is even more awkward.

Curl is made to be scriptable, and also has the merit that you can easily switch to other protocols later by just modifying the URL. If you put your FTP credentials in your .netrc, you can simply do:

# Download file
curl --netrc --remote-name ftp://ftp.example.com/file.bin
# Upload file
curl --netrc --upload-file file.bin ftp://ftp.example.com/

If you must, you can specify username and password directly on the command line using --user username:password instead of --netrc.

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

How to disable/enable select field using jQuery?

sorry for answering in old thread but may my code helps other in future.i was in same scenario that when check box will be checked then few selected inputs fields will be enable other wise disabled.

$("[id*='chkAddressChange']").click(function () {
    var checked = $(this).is(':checked');
    if (checked) {
        $('.DisabledInputs').removeAttr('disabled');
    } else {
        $('.DisabledInputs').attr('disabled', 'disabled');
    }
});

How to wrap text using CSS?

If you type "AAAAAAAAAAAAAAAAAAAAAARRRRRRRRRRRRRRRRRRRRRRGGGGGGGGGGGGGGGGGGGGG" this will produce:

AARRRRRRRRRRRRRRRRRRRR
RRGGGGGGGGGGGGGGGGGGGG
G

I have taken my example from a couple different websites on google. I have tested this on ff 5.0, IE 8.0, and Chrome 10. It works on all of them.

.wrapword {
    white-space: -moz-pre-wrap !important;  /* Mozilla, since 1999 */
    white-space: -pre-wrap;      /* Opera 4-6 */
    white-space: -o-pre-wrap;    /* Opera 7 */
    white-space: pre-wrap;       /* css-3 */
    word-wrap: break-word;       /* Internet Explorer 5.5+ */
    white-space: -webkit-pre-wrap; /* Newer versions of Chrome/Safari*/
    word-break: break-all;
    white-space: normal;
}

<table style="table-layout:fixed; width:400px">
    <tr>
        <td class="wrapword"></td>
    </tr>
</table>

SQL Error: ORA-00942 table or view does not exist

Issue could be with different table(might not exists or grant privilege is not for that table) mapped due to foreign key or synonym.

For me the issue was with a column in that table which had mapping with another schema-table, and it was missing.ex, public-synonym.

Uses of content-disposition in an HTTP response header

Note that RFC 6266 supersedes the RFCs referenced below. Section 7 outlines some of the related security concerns.

The authority on the content-disposition header is RFC 1806 and RFC 2183. People have also devised content-disposition hacking. It is important to note that the content-disposition header is not part of the HTTP 1.1 standard.

The HTTP 1.1 Standard (RFC 2616) also mentions the possible security side effects of content disposition:

15.5 Content-Disposition Issues

RFC 1806 [35], from which the often implemented Content-Disposition
(see section 19.5.1) header in HTTP is derived, has a number of very
serious security considerations. Content-Disposition is not part of
the HTTP standard, but since it is widely implemented, we are
documenting its use and risks for implementors. See RFC 2183 [49]
(which updates RFC 1806) for details.

How can I completely remove TFS Bindings

Sometime, the binding info is cached

To clear Team Explorer's cache:

Go to C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\2.0
Delete or rename the Cache folder.

This come from a website I could not find now. Thanks for that guy for the tip.

What does "pending" mean for request in Chrome Developer Window?

In my case, I found (after much hair-pulling) that the "pending" status was caused by the AdBlock extension. The image that I couldn't get to load had the word "ad" in the URL, so AdBlock kept it from loading.

Disabling AdBlock fixes this issue.

Renaming the file so that it doesn't contain "ad" in the URL also fixes it, and is obviously a better solution. Unless it's an advertisement, in which case you should leave it like that. :)

SVN change username

for Win10 you should remove this folder and close/open your IDE

C:\Users\User\AppData\Roaming\Subversion\auth

, also in my projects no ".subversion" folders, only ".svn"

PHP AES encrypt / decrypt

If you are using MCRYPT_RIJNDAEL_128, try rtrim($output, "\0\3"). If the length of the string is less than 16, the decrypt function will return a string with length of 16 characters, adding 03 at the end.

You can easily check this, e.g. by trying:

$string = "TheString";
$decrypted_string = decrypt_function($stirng, $key);

echo bin2hex($decrypted_string)."=".bin2hex("TheString");

Algorithm to generate all possible permutations of a list?

Here is the code in Python to print all possible permutations of a list:

def next_perm(arr):
    # Find non-increasing suffix
    i = len(arr) - 1
    while i > 0 and arr[i - 1] >= arr[i]:
        i -= 1
    if i <= 0:
        return False

    # Find successor to pivot
    j = len(arr) - 1
    while arr[j] <= arr[i - 1]:
        j -= 1
    arr[i - 1], arr[j] = arr[j], arr[i - 1]

    # Reverse suffix
    arr[i : ] = arr[len(arr) - 1 : i - 1 : -1]
    print arr
    return True

def all_perm(arr):
    a = next_perm(arr)
    while a:
        a = next_perm(arr)
    arr = raw_input()
    arr.split(' ')
    arr = map(int, arr)
    arr.sort()
    print arr
    all_perm(arr)

I have used a lexicographic order algorithm to get all possible permutations, but a recursive algorithm is more efficient. You can find the code for recursive algorithm here: Python recursion permutations

PHP Adding 15 minutes to Time value

Quite easy

$timestring = '09:15:00';
echo date('h:i:s', strtotime($timestring) + (15 * 60));

Git undo changes in some files

git add B # Add it to the index
git reset A # Remove it from the index
git commit # Commit the index

Name node is in safe mode. Not able to leave

The Command did not work for me but the following did

hdfs dfsadmin -safemode leave

I used the hdfs command instead of the hadoop command.

Check out http://ask.gopivotal.com/hc/en-us/articles/200933026-HDFS-goes-into-readonly-mode-and-errors-out-with-Name-node-is-in-safe-mode- link too

Can't start Tomcat as Windows Service

  1. Check the apache tomcat catalina log: ../logs/catalina.log
  2. If in the log you find the "port was used" exception, then Check windows used ports and processes with following command: Run cmd netstat -ao it will list all listening ports and corresponding process Id, you can find the port which was used by Tomcat from the configuration file: ../conf/server.xml

    <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
    

and kill the process which use the tomcat port

Android Studio 3.0 Execution failed for task: unable to merge dex

Use multiDexEnabled true as below.

{
 minSdkVersion 17
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}

and

implementation 'com.android.support:multidex:1.0.3'

this Solution worked for me.

How can I remove a commit on GitHub?

Find the ref spec of the commit you want to be the head of your branch on Github and use the following command:

git push origin +[ref]:[branchName]

In your case, if you just want to go back one commit, find the beginning of the ref for that commit, say for example it is 7f6d03, and the name of the branch you want to change, say for example it is master, and do the following:

git push origin +7f6d03:master

The plus character is interpreted as --force, which will be necessary since you are rewriting history.

Note that any time you --force a commit you could potentially rewrite other peoples' history who merge your branch. However, if you catch the problem quickly (before anyone else merges your branch), you won't have any issues.

Search for an item in a Lua list

Sort of solution using metatable...

local function preparetable(t)
 setmetatable(t,{__newindex=function(self,k,v) rawset(self,v,true) end})
end

local workingtable={}
preparetable(workingtable)
table.insert(workingtable,123)
table.insert(workingtable,456)

if workingtable[456] then
...
end

Best radio-button implementation for IOS

I've written a controller for handling the logic behind an array of radio buttons. It's open source and on GitHub, check it out!

https://github.com/goosoftware/GSRadioButtonSetController

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

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

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

0*[5-9]\d

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

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

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

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

That's it!

.trim() in JavaScript not working in IE

I don't think there's a native trim() method in the JavaScript standard. Maybe Mozilla supplies one, but if you want one in IE, you'll need to write it yourself. There are a few versions on this page.

How can I catch an error caused by mail()?

PHPMailer handles errors nicely, also a good script to use for sending mail via SMTP...

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

Redirection of standard and error output appending to the same log file

Maybe it is not quite as elegant, but the following might also work. I suspect asynchronously this would not be a good solution.

$p = Start-Process myjob.bat -redirectstandardoutput $logtempfile -redirecterroroutput $logtempfile -wait
add-content $logfile (get-content $logtempfile)

How to display images from a folder using php - PHP

You had a mistake on the statement below. Use . not ,

echo '<img src="', $dir, '/', $file, '" alt="', $file, $

to

echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $

and

echo 'Directory \'', $dir, '\' not found!';

to

echo 'Directory \''. $dir. '\' not found!';

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

If you want to understand AutoResetEvent and ManualResetEvent you need to understand not threading but interrupts!

.NET wants to conjure up low-level programming the most distant possible.

An interrupts is something used in low-level programming which equals to a signal that from low became high (or viceversa). When this happens the program interrupt its normal execution and move the execution pointer to the function that handles this event.

The first thing to do when an interrupt happend is to reset its state, becosa the hardware works in this way:

  1. a pin is connected to a signal and the hardware listen for it to change (the signal could have only two states).
  2. if the signal changes means that something happened and the hardware put a memory variable to the state happened (and it remain like this even if the signal change again).
  3. the program notice that variable change states and move the execution to a handling function.
  4. here the first thing to do, to be able to listen again this interrupt, is to reset this memory variable to the state not-happened.

This is the difference between ManualResetEvent and AutoResetEvent.
If a ManualResetEvent happen and I do not reset it, the next time it happens I will not be able to listen it.

Initializing data.frames()

> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300

Finding element's position relative to the document

For those that want to get the x and y coordinates of various positions of an element, relative to the document.

const getCoords = (element, position) => {
  const { top, left, width, height } = element.getBoundingClientRect();
  let point;
  switch (position) {
    case "top left":
      point = {
        x: left + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "top center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "top right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + window.pageYOffset
      };
      break;
    case "center left":
      point = {
        x: left + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "center right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + height / 2 + window.pageYOffset
      };
      break;
    case "bottom left":
      point = {
        x: left + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
    case "bottom center":
      point = {
        x: left + width / 2 + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
    case "bottom right":
      point = {
        x: left + width + window.pageXOffset,
        y: top + height + window.pageYOffset
      };
      break;
  }
  return point;
};

Usage

  • getCoords(document.querySelector('selector'), 'center')

  • getCoords(document.querySelector('selector'), 'bottom right')

  • getCoords(document.querySelector('selector'), 'top center')

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

Be aware, using NSAllowsArbitraryLoads = true in the project's info.plist allows all connection to any server to be insecure. If you want to make sure only a specific domain is accessible through an insecure connection, try this:

enter image description here

Or, as source code:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>domain.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

Clean & Build project after editing.

Java 8 lambda get and remove element from list

As others have suggested, this might be a use case for loops and iterables. In my opinion, this is the simplest approach. If you want to modify the list in-place, it cannot be considered "real" functional programming anyway. But you could use Collectors.partitioningBy() in order to get a new list with elements which satisfy your condition, and a new list of those which don't. Of course with this approach, if you have multiple elements satisfying the condition, all of those will be in that list and not only the first.

Using Python 3 in virtualenv

This is all you need, in order to run a virtual environment in python / python3

First if virtualenv not installed, run

pip3 install virtualenv 

Now Run:

virtualenv -p python3 <env name> 

Sometime the cmd virtualenv fails, if so use this:

python3 -m virtualenv <env_name>  # you can specify full path instead <env_name> to install the file in a different location other than the current location

Now activate the virtual env:

source <env_name>/bin/activate

Or:

source `pwd`/<env_name>/bin/activate

Now run

which python

You should see the full path to your dir and <env_name>/bin/python suffix

To exit the virtualenv, run:

deactivate 

HTML text input field with currency symbol

Use a parent .input-icon div. Optionally add .input-icon-right.

<div class="input-icon">
  <input type="text">
  <i>$</i>
</div>

<div class="input-icon input-icon-right">
  <input type="text">
  <i>€</i>
</div>

Align the icon vertically with transform and top, and set pointer-events to none so that clicks focus on the input. Adjust the padding and width as appropriate:

.input-icon {
  position: relative;
}

.input-icon > i {
  position: absolute;
  display: block;
  transform: translate(0, -50%);
  top: 50%;
  pointer-events: none;
  width: 25px;
  text-align: center;
  font-style: normal;
}

.input-icon > input {
  padding-left: 25px;
  padding-right: 0;
}

.input-icon-right > i {
  right: 0;
}

.input-icon-right > input {
  padding-left: 0;
  padding-right: 25px;
  text-align: right;
}

Unlike the accepted answer, this will retain input validation highlighting, such as a red border when there's an error.

JSFiddle usage example with Bootstrap and Font Awesome

Easiest way to compare arrays in C#

You can use Enumerable.Intersect:

int[] array1 = new int[] { 1, 2, 3, 4,5 },
      array2 = new int[] {7,8};

if (array1.Intersect(array2).Any())
    Console.WriteLine("matched");
else
    Console.WriteLine("not matched");

How do I run a file on localhost?

i am working in VScode currently. i was wanting to run my html page just to see all my main elements.

1) first, in vs, right click desired html file and choose "copy path". do not choose relative.

2) finally, paste html path in address bar (i used chrome) and hit enter. your html page should display. hope this helps someone out.

Plotting of 1-dimensional Gaussian distribution function

You are missing a parantheses in the denominator of your gaussian() function. As it is right now you divide by 2 and multiply with the variance (sig^2). But that is not true and as you can see of your plots the greater variance the more narrow the gaussian is - which is wrong, it should be opposit.

So just change the gaussian() function to:

def gaussian(x, mu, sig):
    return np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.)))

Eslint: How to disable "unexpected console statement" in Node.js?

For vue-cli 3 open package.json and under section eslintConfig put no-console under rules and restart dev server (npm run serve or yarn serve)

...
"eslintConfig": {
    ...
    "rules": {
      "no-console": "off"
    },
    ...

C - freeing structs

You can't free types that aren't dynamically allocated. Although arrays are syntactically similar (int* x = malloc(sizeof(int) * 4) can be used in the same way that int x[4] is), calling free(firstName) would likely cause an error for the latter.

For example, take this code:

int x;
free(&x);

free() is a function which takes in a pointer. &x is a pointer. This code may compile, even though it simply won't work.

If we pretend that all memory is allocated in the same way, x is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope. You can't free the same resource twice; it'll give you an error.

This isn't even mentioning the fact that for certain reasons, you may be unable to free the memory at x without closing the program.

tl;dr: Just free the struct and you'll be fine. Don't call free on arrays; only call it on dynamically allocated memory.

Difference between <? super T> and <? extends T> in Java

You can go through all the answers above to understand why the .add() is restricted to '<?>', '<? extends>', and partly to '<? super>'.

But here's the conclusion of it all if you want to remember it, and dont want to go exploring the answer every time:

List<? extends A> means this will accept any List of A and subclass of A. But you cannot add anything to this list. Not even objects of type A.

List<? super A> means this will accept any list of A and superclass of A. You can add objects of type A and its subclasses.

Bootstrap: adding gaps between divs

The easiest way to do it is to add mb-5 to your classes. That is <div class='row mb-5'>.

NOTE:

  • mb varies betweeen 1 to 5
  • The Div MUST have the row class

How to combine two or more querysets in a Django view?

You can use the QuerySetChain class below. When using it with Django's paginator, it should only hit the database with COUNT(*) queries for all querysets and SELECT() queries only for those querysets whose records are displayed on the current page.

Note that you need to specify template_name= if using a QuerySetChain with generic views, even if the chained querysets all use the same model.

from itertools import islice, chain

class QuerySetChain(object):
    """
    Chains multiple subquerysets (possibly of different models) and behaves as
    one queryset.  Supports minimal methods needed for use with
    django.core.paginator.
    """

    def __init__(self, *subquerysets):
        self.querysets = subquerysets

    def count(self):
        """
        Performs a .count() for all subquerysets and returns the number of
        records as an integer.
        """
        return sum(qs.count() for qs in self.querysets)

    def _clone(self):
        "Returns a clone of this queryset chain"
        return self.__class__(*self.querysets)

    def _all(self):
        "Iterates records in all subquerysets"
        return chain(*self.querysets)

    def __getitem__(self, ndx):
        """
        Retrieves an item or slice from the chained set of results from all
        subquerysets.
        """
        if type(ndx) is slice:
            return list(islice(self._all(), ndx.start, ndx.stop, ndx.step or 1))
        else:
            return islice(self._all(), ndx, ndx+1).next()

In your example, the usage would be:

pages = Page.objects.filter(Q(title__icontains=cleaned_search_term) |
                            Q(body__icontains=cleaned_search_term))
articles = Article.objects.filter(Q(title__icontains=cleaned_search_term) |
                                  Q(body__icontains=cleaned_search_term) |
                                  Q(tags__icontains=cleaned_search_term))
posts = Post.objects.filter(Q(title__icontains=cleaned_search_term) |
                            Q(body__icontains=cleaned_search_term) | 
                            Q(tags__icontains=cleaned_search_term))
matches = QuerySetChain(pages, articles, posts)

Then use matches with the paginator like you used result_list in your example.

The itertools module was introduced in Python 2.3, so it should be available in all Python versions Django runs on.

PHP code is not being executed, instead code shows on the page

This was in my .htaccess

DirectoryIndex index.html index.htm

index.html contained PHP code. By default, PHP won't process files with extentions like htm* as PHP code.

You can override this, by adding the following to .htaccess:

<FilesMatch ".+\.html$">
    SetHandler application/x-httpd-php
</FilesMatch>

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

SQL - How to find the highest number in a column?

If you are using AUTOINCREMENT, use:

SELECT LAST\_INSERT\_ID();

Assumming that you are using Mysql: http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

Postgres handles this similarly via the currval(sequence_name) function.

Note that using MAX(ID) is not safe, unless you lock the table, since it's possible (in a simplified case) to have another insert that occurs before you call MAX(ID) and you lose the id of the first insert. The functions above are session based so if another session inserts you still get the ID that you inserted.

Push JSON Objects to array in localStorage

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

Step 2:

Modify your function like so:

function SaveDataToLocalStorage(data)
{
    var a = [];
    // Parse the serialized data back into an aray of objects
    a = JSON.parse(localStorage.getItem('session')) || [];
    // Push the new data (whether it be an object or anything else) onto the array
    a.push(data);
    // Alert the array value
    alert(a);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    localStorage.setItem('session', JSON.stringify(a));
}

This should take care of the rest for you. When you parse it out, it will become an array of objects.

Hope this helps.

Which characters are valid/invalid in a JSON key name?

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.

Example:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

What does $(function() {} ); do?

$(function() { ... });

is just jQuery short-hand for

$(document).ready(function() { ... });

What it's designed to do (amongst other things) is ensure that your function is called once all the DOM elements of the page are ready to be used.

However, I don't think that's the problem you're having - can you clarify what you mean by 'Somehow, some functions are cannot be called and I have to call those function inside' ? Maybe post some code to show what's not working as expected ?

Edit: Re-reading your question, it could be that your function is running before the page has finished loaded, and therefore won't execute properly; putting it in $(function) would indeed fix that!

Checking if a key exists in a JS object

You can try this:

const data = {
  name : "Test",
  value: 12
}

if("name" in data){
  //Found
}
else {
  //Not found
}